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 窗体应用,用作非常简单的文本文件编辑器。 如果文本框中的文本尚未保存,应用将每隔一分钟询问用户是否要保存文本框的内容。 为此,属性 Interval 设置为 1 分钟 (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

该示例要求将以下控件添加到窗体:

  • 名为 TextBoxTextBox1 的控件 (其默认名称) 。

  • 名为 ButtonButton1 的控件 (其默认名称) 。

  • 名为 SaveFileDialogSaveSaveFileDialog1 的控件 (其默认名称) 。

注解

当 为 nullSynchronizingObject,将在系统线程池中的Elapsed线程上调用处理事件的方法。 有关系统线程池的详细信息,请参阅 ThreadPool

Elapsed当事件由视觉对象Windows 窗体组件(例如按钮)处理时,通过系统线程池访问组件可能会导致异常,或者可能不起作用。 通过将 设置为 SynchronizingObject Windows 窗体 组件来避免此影响,这会导致在创建组件的同一线程上调用处理Elapsed事件的方法。

注意

即使 SynchronizingObject 属性不null为 ,Elapsed事件也可能在调用 或 Stop 方法后发生,或者将 属性设置为 falseEnabled发生Dispose,因为引发事件的Elapsed信号始终在线程池线程上排队等待执行。 解决此争用条件的一种方法是设置一个标志,指示事件的事件处理程序 Elapsed 忽略后续事件。

Timer如果在 visual Studio 中Windows 窗体设计器中使用 , SynchronizingObject 将自动设置为包含 的 Timer控件。 例如,如果将 (从) 继承的设计器Form1上放置 Timer ,则 SynchronizingObjectTimer 属性设置为 的Form1实例。Form

适用于

另请参阅