当另一个线程正在执行任务时暂停线程
本文关键字:线程 暂停 执行任务 另一个 | 更新日期: 2023-09-27 18:11:32
我创建了一个执行任务的线程,但是我需要暂停我的主线程,直到我的次级线程结束任务。
private void AquilesPL_Load(object sender, EventArgs e)
{
ThreadStart ts = new ThreadStart(RunTask)
Thread t = new Thread(ts);
t.Start();
SomeFunction1();
SomeFunction2();
//I need to pause the main thread here, if runtask() continue working
//if runt task ends, this main thread must to continue.
ReadFile();
CloseProgram();
}
private void RunTask()
{
//Some code that write a file
//RunTaskfunction ends, and i have to continue
}
private void ReadFile()
{
//Reading the file, this file has been written by RunTask
}
但是我需要暂停我的主线程,直到我的次要线程结束任务。
这通常是一个坏主意。一个更好的解决方案是在任务执行时禁用UI,然后在任务完成时重新启用它。
TPL和async/await使得这相当简单。例如:
private async void AquilesPL_Load(object sender, EventArgs e)
{
var task = Task.Run(() => RunTask());
SomeFunction1();
SomeFunction2();
// Disable your UI controls
await task; // This will wait until the task completes,
// but do it asynchronously so it does not block the UI thread
// This won't read until the other task is done
ReadFile();
// Enable your UI controls here
}
如果你不能使用c# 5,你可以通过。net 4和TPL:
private void AquilesPL_Load(object sender, EventArgs e)
{
var task = Task.Factory.StartNew(() => RunTask());
SomeFunction1();
SomeFunction2();
// Disable your UI controls
task.ContinueWith(t =>
{
// This won't read until the other task is done
ReadFile();
// Enable your UI controls here
}, TaskScheduler.FromCurrentSynchronizationContext());
}