Question : How to monitor if a Thread completed?

I hope someone has a good answer to this question.
I have an application that grabs some data and shows a report. The process of comping the report takes about 20 minutes and I want the user to be able to click a Cancel command to stop this.

I want to use the .NET 4.0 Cancellation Token. My main problem is not cancelling the thread that is fetching the data, but once the thread actually completes and updates the dataset with all the informatin. How do I let the application know that the first thread completed?  What is the best practice to do this? Keeping in mind that my application needs to remain responsive for the user.

If anyone has some experience with this type of a setup, I would welcome your input.

Thank you.

Answer : How to monitor if a Thread completed?

What you want to do is call the method (your longrunningtask) using an asynchronous delegate. This is better than normal multithreading (using the threadpool for example) in that one can get exceptions thrown on the original thread back to the caller when the caller re-unites with the delegate (in EndInvoke). The caller can then rethrow the exception (something not possible in normal threading usage).

This example assumes that your LongRunningProcess returns a string (but that can be changed in the delegate definition).

Also - if you are doing this from a UI control (a WinForm for example) - a BackgroundWorker is the way to go. It has built in cancellation and progress notification capabilities - and is extremely straightforward to use. It keeps the UI responsive while delegating the background task.
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
delegate string LongRunningTask(CancellationToken ct);

static void MainMethod() {

 CancellationToken ct = tokenSource2.Token;
// Instantiate delegates with  LongRunningTask's signature:  
LongRunningTask task1 = LongRunningProcess(ct);

// Start the invocation
 IAsyncResult cookie = task1.BeginInvoke (ct, null, null);
 
// Can do something else here if needed (PerformOtherTask())
// PerformOtherTask();

 // Get the results of the LongRunningProcess, waiting for completion if necessary.
 // Here is where any exceptions will be thrown:

 try
  {
    string s1 = task1.EndInvoke (cookie);
  }
 catch(Exception e)
  {
    throw;
  }

}
Random Solutions  
 
programming4us programming4us