[英]How to Start/Stop/Wait for a Thread
I am porting some C# .Net code to WinRT and I am having trouble figuring out how to replace the following: 我正在将一些C#.Net代码移植到WinRT,我无法确定如何替换以下内容:
bool threadDone = false;
Thread updateThread = null;
void StartUpdateThread() {
threadDone = false;
updateThread = new Thread(new ThreadStart(SendUpdateThread));
updateThread.Start();
}
void StopUpdateThread() {
if (updateThread == null) return;
threadDone = true;
updateThread.Join();
updateThread = null;
}
void SendUpdateThread() {
while(!threadDone) {
...
Thread.Sleep(...);
}
}
What is the best way to replace this in WinRT. 在WinRT中替换它的最佳方法是什么。 I have looked at ThreadPool.RunAsync(...) to start the code running, but I am not sure of the best wait to stop it and wait for its completion in StopUpdateThread.
我已经看过ThreadPool.RunAsync(...)来启动代码运行,但我不确定最好等待它停止并等待它在StopUpdateThread中完成。 Also, what do I replace the sleep with in my thread function?
另外,我在我的线程函数中用什么替换睡眠?
Since we're talking about C# 5 GUI application, it would be probably best if you didn't block anything and used Task
s and async
- await
instead. 由于我们讨论的是C#5 GUI应用程序,如果你没有阻塞任何东西并且使用了
Task
和async
,那么最好是await
。 That could look something like this: 这可能看起来像这样:
// I think this field needs to be volatile even in your version
volatile bool taskDone = false;
Task updateTask = null;
void StartUpdateTask() {
taskDone = false;
updateTask = Task.Run(SendUpdateTask);
}
async Task StopUpdateTask() {
if (updateTask == null) return;
taskDone = true;
await updateTask;
updateTask = null;
}
async Task SendUpdateTask() {
while (!taskDone) {
...
await Task.Delay(…);
}
}
But to use this code correctly, you actually need to understand what async
- await
does, so you should read up about that. 但是要正确使用这段代码,你实际上需要了解
async
- await
是什么,所以你应该读一下。
Also, this might not be exactly what you need, but that's hard to know based just on the information in your question. 此外,这可能不是您所需要的,但仅根据您问题中的信息很难知道。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.