doc*_*lic 3 c# multithreading timer
我的System.Threading.Timer(有一个回调)永远不会可靠地触发.这是我的编程任务的一部分,我输入计时器应该从文本框运行的时间量.
计时器声明如下:
System.Threading.Timer timer = new System.Threading.Timer(WorkerObject.callback, null, delay, Timeout.Infinite);
Run Code Online (Sandbox Code Playgroud)
而延迟只是int描述第一次触发回调的延迟(它只能触发一次).
回调方法是这样的:
public static void callback(Object stateinfo)
{
stop = true;
}
Run Code Online (Sandbox Code Playgroud)
所有这一切都设置了一个标志为true,它停止循环(由ThreadPool上的线程运行,实际上,停止线程).
循环看起来像这样:
while (!stop)
{
currentTextbox.Invoke(new Action(delegate()
{
currentTextbox.AppendText((counter++) + Environment.NewLine);
currentTextbox.Update();
}));
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,stop对于超过5000毫秒的任何延迟,变量总是为假.有没有办法"强迫"回调始终开火?
我建议使用CancellationTokenSource:
static CancellationTokenSource Cancel = new CancellationTokenSource();
public static void Callback(object state)
{
Cancel.Cancel();
}
Run Code Online (Sandbox Code Playgroud)
和你的循环:
while (!Cancel.IsCancellationRequested)
{
...
}
Run Code Online (Sandbox Code Playgroud)
这比使用volatile更简洁,并且当您将简单的概念证明移动到单独的类时更容易移植。有关更多信息,请参阅我的博客Polling for Cancellation。
| 归档时间: |
|
| 查看次数: |
3437 次 |
| 最近记录: |