如何启动一个线程/停止/等待 [英] How to Start/Stop/Wait for a Thread
问题描述
我移植一些C#.NET code到的WinRT和我有麻烦搞清楚如何更换以下内容:
I am porting some C# .Net code to WinRT and I am having trouble figuring out how to replace the following:
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(...);
}
}
什么是WinRT的更换最好的方法。我已经看过ThreadPool.RunAsync(...)启动code运行,但我不知道最好等待阻止它,并等待其完成StopUpdateThread。另外,我该怎么跟我的线程函数替换睡眠?
What is the best way to replace this in 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. Also, what do I replace the sleep with in my thread function?
推荐答案
由于我们正在谈论C#5 GUI应用程序,这将是可能是最好的,如果你没有阻止任何东西,使用任务
和异步
- 等待
来代替。这可能是这个样子:
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. 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(…);
}
}
但要正确使用此code,你真正需要了解异步
- 等待
呢,所以你应该读了这一点。
But to use this code correctly, you actually need to understand what async
-await
does, so you should read up about that.
此外,这可能不是正是你需要的,但是这是很难根据只是在你的问题中的信息就知道了。
Also, this might not be exactly what you need, but that's hard to know based just on the information in your question.
这篇关于如何启动一个线程/停止/等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!