我有一个函数,我在c#.net。
中使用了一个线程我在该线程的下一行有另一个函数。但是只有在线程执行后才能调用此函数。
我该怎么做?
实施例..
Somefunction()
{
// thread //(thread started)
add() (another function but need to be executed only tha above thread gets over)
}
答案 0 :(得分:5)
使用BackgroundWorker并在worker completeted事件处理程序中包含函数调用。
var worker = new BackgroundWorker();
_worker.DoWork += delegate { DoStuff(); };
_worker.RunWorkerCompleted += worker_RunWorkerCompleted;
_worker.RunWorkerAsync();
[...]
private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
/// Do post-thread stuff
}
答案 1 :(得分:3)
使用Thread.Join阻止当前线程,直到指定的线程完成执行。
答案 2 :(得分:2)
如果您希望执行是单线程的,为什么要启动一个单独的线程?
答案 3 :(得分:1)
通过“线程执行后”,你的意思是它必须启动吗?或者必须完成?
如果你的意思已经完成,那么你通常会Join()
线程 - 但是你之前没有看到Join()
线程中的线程(只是直接执行代码)。另一种方法是在线程方法的末尾使用“回调”。
如果您的意思是开始,那么您可以执行以下操作:
object lockObj = new object();
lock(lockObj) {
ThreadPool.QueueUserWorkItem(delegate {
lock(lockObj) {
Monitor.Pulse(lockObj);
}
// do things (we're on the second thread...)
});
Monitor.Wait(lockObj);
}
// thread has definitely started here
答案 4 :(得分:0)
例如,您可以使用ManualResetEvent。 当您在另一个线程上开始处理时,您将调用reset方法。 当其他线程上的处理完成后,您调用set。 然后,必须在'主线程'上执行的方法需要等待,直到设置了ManualResetEvent才能执行。
有关详细信息,您可以查看MSDN上的the ManualResetEvent。
答案 5 :(得分:0)
如果add()是线程安全的,只需在传递的函数末尾调用它来创建线程。
答案 6 :(得分:0)
您可以尝试以下操作,它可能不适用于您的场景:鉴于您提供的详细信息,我无法分辨:
首先创建一个委托:
public delegate int MyThreadSignature(Something arg);
然后使用Begin / End Invoke模式:
var thread = new MyThreadSignature(WorkerMethod);
thread.BeginInvoke(theArg,
MyThreadEnded, /*Method to call when done*/,
thread /*AsyncState*/);
创建MyThreadEnded方法:
void MyThreadEnded(IAsyncResult result)
{
var thread = (MyThreadSignature)result.AsyncState;
var result = thread.EndInvoke(result);
// Call your next worker here.
}
调用 MUST 的方法在示例中有签名:Name(IAsyncResult result)。