使用计时器和2个按钮进行跨线程操作无效 [英] Cross-thread operation not valid using timer and 2 buttons
问题描述
我遇到了这个问题...
i got this problem...
对此有什么好的解决方案?
What would be a good solution for this?
private void button1_Click(object sender, EventArgs e)
{
aTimer.Enabled = true;
button1.Enabled = false;
}
private void button2_Click(object sender, EventArgs e)
{
aTimer.Enabled = false;
}
private void timer_is_working(object source, ElapsedEventArgs e)
{
aTimer.Enabled = false;
button1.Enabled = true;
}
谢谢!亲切的问候丹尼尔·鲁舍(Daniel Ruescher)
Thanks! Kind regards Daniel Ruescher
推荐答案
所以您不清楚,但是根据 ElapsedEventArgs
类型,看来 timer_is_working
是 System.Timers.Timer
实例的 Elapsed
事件.
So you did not make it clear, but based on the ElapsedEventArgs
type it seems that timer_is_working
is the Elapsed
event of a System.Timers.Timer
instance.
请注意,.NET Framework类库包括四个类名为Timer的计时器,每个计时器提供不同的功能:
Be aware that the .NET Framework Class Library includes four classes named Timer, each of which offers different functionality:
- System.Timers.Timer:定期触发一个事件.该类旨在用作基于服务器或服务的多线程环境中的组件.
- System.Threading.Timer:定期在线程池线程上执行单个回调方法.回调方法是在计时器实例化且无法更改时定义.喜欢System.Timers.Timer类,该类旨在用作多线程环境中基于服务器或服务的组件.
- System.Windows.Forms.Timer:一个Windows Forms组件,该组件定期触发事件.该组件设计用于单线程环境.
- System.Web.UI.Timer:一个ASP.NET组件,该组件定期执行异步或同步网页回发.
如果这是Windows.Forms应用程序,请改用 System.Windows.Forms.Timer
(可在工具箱/组件"中找到).其 Tick
事件在UI线程中引发,因此可以从那里访问您的控件.
If this is a Windows.Forms app, use a System.Windows.Forms.Timer
instead (you find it in Toolbox/Components). Its Tick
event is raised in the UI thread so can access your controls from there.
如果出于特殊原因需要使用 System.Timers.Timer
(例如,精度),则必须将访问权限包装为 Invoke
调用:
If you have a special reason to use the System.Timers.Timer
(eg. precision), you must wrap your access into an Invoke
call:
Invoke(new Action(() => { button1.Enabled = true; }));
这篇关于使用计时器和2个按钮进行跨线程操作无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!