C# 如何为计时器使用安全线程(从不同线程更改计时器属性)
要访问表单上的备忘录,我使用以下代码C# 如何为计时器使用安全线程(从不同线程更改计时器属性),c#,winforms,multithreading,timer,C#,Winforms,Multithreading,Timer,要访问表单上的备忘录,我使用以下代码 public string TextValue { set { if (this.Memo.InvokeRequired) { this.Invoke((MethodInvoker)delegate { this.Memo.Text += value + "\n
public string TextValue
{
set
{
if (this.Memo.InvokeRequired)
{
this.Invoke((MethodInvoker)delegate
{
this.Memo.Text += value + "\n";
});
}
else
{
this.Memo.Text += value + "\n";
}
}
}
我想使用相同的代码来启用/禁用计时器,但计时器不需要属性invokererequired
public int Timer
{
set
{
if (this.timer.InvokeRequired) //?? No such thing
{
this.Invoke((MethodInvoker)delegate
{
if (value == 1)
this.timer.Enabled = true;
else
this.timer.Enabled = false;
});
}
else
{
if (value == 1)
this.timer.Enabled = true;
else
this.timer.Enabled = false;
}
}
}
如何从其他线程启用计时器?这是表单对象吗
假设您使用表单设计器创建了计时器对象,那么该对象是由创建表单的线程创建的,因此检查表单的invokererequired属性可以有效地告诉您相同的事情。这是表单对象吗
假设您使用表单设计器创建了计时器对象,那么该对象是由创建表单的线程创建的,因此检查表单的InvokeRequest属性可以有效地告诉您同样的事情。从代码中删除计时器,如下所示:
public int Timer
{
set
{
if (this.InvokeRequired)
{
this.Invoke((MethodInvoker)delegate
{
if (value == 1)
this.timer.Enabled = true;
else
this.timer.Enabled = false;
});
}
else
{
if (value == 1)
this.timer.Enabled = true;
else
this.timer.Enabled = false;
}
}
}
从代码中删除计时器,如下所示:
public int Timer
{
set
{
if (this.InvokeRequired)
{
this.Invoke((MethodInvoker)delegate
{
if (value == 1)
this.timer.Enabled = true;
else
this.timer.Enabled = false;
});
}
else
{
if (value == 1)
this.timer.Enabled = true;
else
this.timer.Enabled = false;
}
}
}
是的,“this”是一个form对象,但我从临界区内的另一个线程调用该函数。这很好。调用所需的所有布尔值都告诉您CurrentThread==ThreadThatCreatedTheObject。创建窗体的线程与创建计时器的线程是同一个线程,因此这将起作用。不,它不起作用。我无法启用计时器。是的,“this”是一个窗体对象,但我正在从关键部分内的不同线程调用该函数。这很好。调用所需的所有布尔值都告诉您CurrentThread==ThreadThatCreatedTheObject。创建窗体的线程与创建计时器的线程是同一个线程,因此这将起作用。不,它不起作用。我无法启用计时器。