Timer.SynchronizingObject Propiedad
Definición
Importante
Parte de la información hace referencia a la versión preliminar del producto, que puede haberse modificado sustancialmente antes de lanzar la versión definitiva. Microsoft no otorga ninguna garantía, explícita o implícita, con respecto a la información proporcionada aquí.
Obtiene o establece el objeto utilizado para serializar las llamadas al controlador de eventos que se emiten cuando ha transcurrido un intervalo.
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
Valor de propiedad
ISynchronizeInvoke que representa el objeto utilizado para serializar las llamadas del controlador de eventos que se emiten cuando ha transcurrido un intervalo. El valor predeterminado es null.
- Atributos
Ejemplos
El ejemplo siguiente es una aplicación de Windows Forms que actúa como un editor de archivos de texto muy sencillo. Cuando no se ha guardado el texto del cuadro de texto, la aplicación pregunta al usuario en intervalos de un minuto si desea guardar el contenido del cuadro de texto. Para ello, la Interval propiedad se establece en un minuto (60 000 milisegundos) y la SynchronizingObject propiedad se establece en el Form objeto .
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
El ejemplo requiere que agregue los siguientes controles al formulario:
Control TextBox denominado
TextBox1(su nombre predeterminado).Control Button denominado
Button1(su nombre predeterminado).Un SaveFileDialog control denominado
SaveSaveFileDialog1(su nombre predeterminado) .
Comentarios
Cuando SynchronizingObject es null, se llama al método que controla el Elapsed evento en un subproceso desde el grupo de subprocesos del sistema. Para obtener más información sobre los grupos de subprocesos del sistema, consulte ThreadPool.
Cuando un componente visual de Windows Forms controla el Elapsed evento, como un botón, el acceso al componente a través del grupo de subprocesos del sistema podría dar lugar a una excepción o simplemente no funcionar. Evite este efecto estableciendo SynchronizingObject en un componente de Windows Forms, lo que hace que se llame al método que controla el Elapsed evento en el mismo subproceso en el que se creó el componente.
Nota:
Incluso si la SynchronizingObject propiedad no nulles , Elapsed los eventos pueden producirse después de llamar al Dispose método o Stop después de que la Enabled propiedad se haya establecido falseen , porque la señal para generar el Elapsed evento siempre se pone en cola para su ejecución en un subproceso del grupo de subprocesos. Una manera de resolver esta condición de carrera es establecer una marca que indique al controlador de eventos que el Elapsed evento omita los eventos posteriores.
Timer Si se usa dentro de Visual Studio en un diseñador de Windows Forms, SynchronizingObject se establece automáticamente en el control que contiene .Timer Por ejemplo, si coloca un Timer en un diseñador para Form1 (que hereda de Form), la SynchronizingObject propiedad de Timer se establece en la instancia de Form1.