Timer.SynchronizingObject 屬性

定義

取得或設定物件,用來封送處理事件處理常式的呼叫 (當間隔已經耗盡時所發出)。

public:
 property System::ComponentModel::ISynchronizeInvoke ^ SynchronizingObject { System::ComponentModel::ISynchronizeInvoke ^ get(); void set(System::ComponentModel::ISynchronizeInvoke ^ value); };
public System.ComponentModel.ISynchronizeInvoke SynchronizingObject { get; set; }
public System.ComponentModel.ISynchronizeInvoke? SynchronizingObject { get; set; }
[System.Timers.TimersDescription("TimerSynchronizingObject")]
public System.ComponentModel.ISynchronizeInvoke SynchronizingObject { get; set; }
[System.Timers.TimersDescription("TimerSynchronizingObject")]
[System.ComponentModel.Browsable(false)]
public System.ComponentModel.ISynchronizeInvoke SynchronizingObject { get; set; }
member this.SynchronizingObject : System.ComponentModel.ISynchronizeInvoke with get, set
[<System.Timers.TimersDescription("TimerSynchronizingObject")>]
member this.SynchronizingObject : System.ComponentModel.ISynchronizeInvoke with get, set
[<System.Timers.TimersDescription("TimerSynchronizingObject")>]
[<System.ComponentModel.Browsable(false)>]
member this.SynchronizingObject : System.ComponentModel.ISynchronizeInvoke with get, set
Public Property SynchronizingObject As ISynchronizeInvoke

屬性值

ISynchronizeInvoke,表示用來封送處理事件處理常式呼叫 (當間隔已經耗盡時所發出) 的物件。 預設為 null

屬性

範例

下列範例是Windows Forms應用程式,可作為非常簡單的文字檔編輯器。 當文字方塊中的文字尚未儲存時,應用程式會以一分鐘間隔詢問使用者是否要儲存文字方塊的內容。 若要這樣做, Interval 屬性會設定為 60,000 毫秒 (60,000 毫秒) ,而 SynchronizingObject 屬性會設定為 Form 物件。

using System;
using System.IO;
using  Timers = System.Timers;
using System.Windows.Forms;
public partial class Form1 : Form
{
    Timers.Timer timer = null;
    StreamWriter sw = null;
    bool hasChanged = false;
    bool dialogIsOpen = false;
    int elapsedMinutes = 0;
    // Cache the text box cache internally without saving it.
    String txt = "";

    public Form1()
    {
        InitializeComponent();

        this.Text = "Quick Text Editor";
        button1.Text = "Save";
        textBox1.Multiline = true;

        // Configure the SaveFile dialog
        saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
        saveFileDialog1.RestoreDirectory = true;

        // Create a timer with a 1-minute interval
        timer = new Timers.Timer(60000);
        // Define the event handler
        timer.Elapsed += this.PromptForSave;
        // Synchronize the timer with the text box
        timer.SynchronizingObject = this;
        // Start the timer
        timer.AutoReset = true;
    }

    private void PromptForSave(Object source, Timers.ElapsedEventArgs e)
    {
        if (hasChanged & (!dialogIsOpen)) {
            elapsedMinutes++;
            dialogIsOpen = true;
            if (MessageBox.Show(String.Format("{0} minutes have elapsed since the text was saved. Save it now? ",
                elapsedMinutes), "Save Text",
                MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                button1_Click(this, EventArgs.Empty);
                dialogIsOpen = false;
            }
        }
    }

    private void button1_Click(Object sender, EventArgs e)
    {
        if (String.IsNullOrEmpty(saveFileDialog1.FileName)) {
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                sw = new StreamWriter(saveFileDialog1.FileName, false);
        }
        txt = textBox1.Text;
        hasChanged = false;
        timer.Stop();
    }

    private void form1_FormClosing(Object sender, FormClosingEventArgs e)
    {
        if (sw != null) {
            sw.Write(txt);
            sw.Close();
        }
    }

    private void textBox1_TextChanged(Object sender, EventArgs e)
    {
        hasChanged = true;
        timer.Start();
    }
}
Imports System.IO
Imports System.Timers

Public Class Form1
   ' Create the timer to fire at a 60-second interval.
   Dim WithEvents timer As New System.Timers.Timer(60000)
   Dim sw As StreamWriter
   Dim hasChanged As Boolean
   Dim dialogIsOpen As Boolean = False
   Dim elapsedMinutes As Integer = 0
   ' Cache the text box internally without saving it.
   Dim txt As String = ""

   Public Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
      Me.Text = "Quick Text Editor"
      Button1.Text = "Save"
      TextBox1.Multiline = True

      ' Configure the SaveFile dialog
      SaveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
      SaveFileDialog1.RestoreDirectory = True

      ' Create a timer with a 1-minute interval
      timer = New Timer(2000)
      ' Synchronize the timer with the text box
      timer.SynchronizingObject = Me
      ' Start the timer
      timer.AutoReset = True
   End Sub

    Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
      hasChanged = True
      timer.Start()
   End Sub
   Friend Sub PromptForSave(sender As Object, e As ElapsedEventArgs) _
      Handles timer.Elapsed
      If hasChanged And Not dialogIsOpen Then
         elapsedMinutes += 1
         dialogIsOpen = True
         If MsgBox(String.Format("{0} minutes have elapsed since the text was saved. Save it now? ",
                                 elapsedMinutes), MsgBoxStyle.YesNoCancel Or MsgBoxStyle.Question,
                   "Save Text") = MsgBoxResult.Yes Then
            If dialogIsOpen Then
               Button1_Click(Me, EventArgs.Empty)
               dialogIsOpen = False
            End If
         End If
      End If
   End Sub

   Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
      If String.IsNullOrEmpty(SaveFileDialog1.FileName) Then
         If SaveFileDialog1.ShowDialog() = DialogResult.OK Then
            sw = New StreamWriter(SaveFileDialog1.FileName, False)
         End If
      End If
      txt = TextBox1.Text
      hasChanged = False
      elapsedMinutes = 0
      timer.Stop()
   End Sub

   Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
      If sw IsNot Nothing Then
         sw.Write(txt)
         sw.Close()
      End If
   End Sub
End Class

此範例會要求您將下列控制項新增至表單:

  • TextBox名為 TextBox1 的控制項 (其預設名稱) 。

  • Button名為 Button1 的控制項 (其預設名稱) 。

  • SaveFileDialog名為 SaveSaveFileDialog1 的控制項 (其預設名稱) 。

備註

當 為 nullSynchronizingObject ,會從系統執行緒集區呼叫處理 Elapsed 事件的方法。 如需系統執行緒集區的詳細資訊,請參閱 ThreadPool

Elapsed當視覺效果Windows Forms元件處理事件時,例如按鈕,透過系統執行緒集區存取元件可能會導致例外狀況,或只是無法運作。 藉由將 設定 SynchronizingObject 為 Windows Forms 元件來避免這個效果,這會導致處理事件的方法 Elapsed 在元件建立所在的相同執行緒上呼叫。

注意

即使 SynchronizingObject 屬性不是 nullElapsed 事件也可能發生在 呼叫 或 Stop 方法之後 Dispose ,或屬性設定為 false 之後 Enabled ,因為引發 Elapsed 事件的訊號一律會排入佇列,以線上程集區執行緒上執行。 解決此競爭條件的其中一種方法是設定旗標,告知事件的事件處理常式 Elapsed 忽略後續事件。

Timer如果在Windows Forms設計工具的 Visual Studio 內使用 , SynchronizingObject 則會自動設定為包含 的 Timer 控制項。 例如,如果您在繼承自 Form) 之 (設計工具 Form1 上放置 Timer ,則 SynchronizingObjectTimer 屬性會設定為 的 Form1 實例。

適用於

另請參閱