How to Start/Stop/Wait for a Thread

淺唱寂寞╮ 提交于 2019-12-11 17:38:43

问题


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(...);
  }
}

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?


回答1:


Since we're talking about C# 5 GUI application, it would be probably best if you didn't block anything and used Tasks 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(…);
  }
}

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.



来源:https://stackoverflow.com/questions/10238662/how-to-start-stop-wait-for-a-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!