如何在特定的线程上过去Timers.Timer? [英] How to elapse Timers.Timer on a specific thread?
问题描述
目标是在我选择的特定线程上超过Timers.Timer。
我需要将ISynchronizeInvoke实例设置为Timer.SynchronizingObject属性。
我需要创建特定线程上的ISynchronizeInvoke实例,但我不能:
public Form1()
{
InitializeComponent();
此 .Load + = 委托
{
new 线程(线程).Start();
};
}
System.Timers.Timer timer = new System.Timers.Timer();
void 线程()
{
ISynchronizeInvoke invoke =?
timer = new System.Timers.Timer();
timer.SynchronizingObject = invoke;
}
}
注意:
下一步不是解决方案:
1.锁定
2. AutoReset
3.未准备好在UI线程上按下按钮等。
我需要在另一个非UI单线程上运行Timers.Timer,就像我在UI线程上运行Windows Forms一样。
< blockquote>你不能告诉它使用哪个线程。 Timer甚至不知道它正在使用哪个线程!从文档:
System.Threading.Timer,它定期在线程池线程上执行单个回调方法。
您无法随时强制线程执行代码。目标线程确定何时接受Invoke。我知道如果做这样的事情的唯一方法是在目标线程中实现一种带有SynchronizationContext的消息泵。
我所知道的最完整的解释这是这里 [ ^ ],附带实施示例。
The goal is to elapse Timers.Timer on a specific thread i choose.
I need to set ISynchronizeInvoke instance to Timer.SynchronizingObject Property.
I need to create ISynchronizeInvoke instance on a the specific thread, but i can't:
public Form1()
{
InitializeComponent();
this.Load += delegate
{
new Thread(Thread).Start();
};
}
System.Timers.Timer timer = new System.Timers.Timer();
void Thread()
{
ISynchronizeInvoke invoke = ?
timer = new System.Timers.Timer();
timer.SynchronizingObject = invoke;
}
}
Notes:
The next ways are not solutions:
1. lock
2. AutoReset
3. Not ready Control like Button to elapse on UI thread.
I need to run Timers.Timer on another not UI single thread like i run Windows Forms on UI thread.
You don't get to tell it which thread to use. The Timer doesn't even know which thread it's doing use! From the documentation:
System.Threading.Timer, which executes a single callback method on a thread pool thread at regular intervals.
You cannot force a thread to execute code whenever you want. The target thread determines when it will accept an Invoke. The only way I know if doing something like this is to implement a kind of message pump with a SynchronizationContext in your target thread.
The most complete explanation I know of for this is here[^], complete with examples of implementation.
这篇关于如何在特定的线程上过去Timers.Timer?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!