I'm writing an application in WPF. I have one main thread and another one - where I calculate something. In main thread I need to do one operation after additional thread will be finished. I can't use Join for additional thread, because I don't want to block main thread. How I can wait for finishing second thread and at the same time don't block main thread?
3 Answers
The eaisest way is to use the backgroundworker and handle the RunWorkerCompleted event.
I also invite you to take a look Part 3 of Joseph Albahari's Threading in C# pdf
2 Comments
ravenik
Hmmm, I think it won't be the best solution. I would like to cancel this additional thread when I click cancel button. I know that background worker has CancelAsync() method, but method that should be done in background worker is running independent. I mean in this function I have no loop which I could break but i just call a system function to optimization and I can't break it.
Conrad Frix
@ravenik. Don't you have this problem regardless of which solution you choose? Is
if (_bw.CancellationPending) { e.Cancel = true; return; } before setting e.result enough for you?Another easy way is to use Task Parallel Library and chain multiple tasks with continuations.
Though it doesn't exempt you from @Conrad's advice: Read the threading book. It's fascinating and totally worth the efforts.
1 Comment
Conrad Frix
@Anvanka +1 continuations are a very nice alternative
If you're creating your own threads, have the worker thread invoke a callback method when it's done:
public delegate void DoneDelegate (object calculationResults);
public class MyWorker
{
public DoneDelegate Done { get; set; }
public void Go()
{
object results = null;
// do some work
Done(results);
}
}
public class Main
{
public void StartWorker()
{
MyWorker worker = new MyWorker();
worker.Done = new DoneDelegate(DoneCallback);
System.Threading.Thread thread = new System.Threading.Thread(worker.Go);
thread.IsBackground = true;
thread.Start();
}
public void DoneCallback (object results)
{
// use the results
}
}