C# 调用完成后返回的线程
我需要从winform应用程序调用一个单独的线程,并等待它,只要它的工作在没有锁定UI的情况下完成,例如:C# 调用完成后返回的线程,c#,multithreading,C#,Multithreading,我需要从winform应用程序调用一个单独的线程,并等待它,只要它的工作在没有锁定UI的情况下完成,例如: // ButtonClick event handler Thread t = new Thread(OnThread); t.Start(); MessageBox.Show("Complete"); voin OnThread() { // some long running work here.. } 因此,当OnThread函数返回时,messagebox应该出现。 想
// ButtonClick event handler
Thread t = new Thread(OnThread);
t.Start();
MessageBox.Show("Complete");
voin OnThread()
{
// some long running work here..
}
因此,当OnThread函数返回时,messagebox应该出现。
想法?这个问题有许多适用的解决方案。您选择的解决方案将取决于代码的语义和目标框架版本 在我们的对话中,最适用的解决方案是在
OnMethod
方法完成后引发一个事件,然后在事件处理程序中编写后续代码,如下所示
private void buttonSomething_Click(object sender, EventArgs eventArgs)
{
OnMethodCompleted += (s, e) =>
{
MessageBox.Show("...");
};
Thread thread = new Thread(OnMethod);
thread.Start();
}
private void OnMethod()
{
// Some long running operation here..
OnMethodCompleted(this, EventArgs.Empty);
}
private static event EventHandler OnMethodCompleted = delegate { };
你可以和代表们一起玩
var threadStart = new ThreadStart(OnThread);
threadStart+= OnThreadEnds;//<--Combine multicast delegate
Thread t = new Thread(threadStart);
t.Start();
void OnThread()
{
// some long running work here..
}
voin OnThreadEnds()
{
// Here pass the control to UI thread and show message box
//MessageBox.Show("Complete");
}
var threadStart=新的threadStart(OnThread);
threadStart+=线程开始//Messagebox只是一个例子。我真的可以执行另一个线程并等待它。我正在使用.NET 4.0还有其他解决方案吗?@bit您可以使用TPL和附带的任务类。更新了我的答案。不使用Task类是否可行?您可以使用后台工作人员
?这是一个基本的。我想使用线程类。我很好奇,我怎么能像任务类已经做的那样,在不冻结UI的情况下等待单独的线程返回呢。