Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 728
  • Last Modified:

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.
0
MDKDevelopers
Asked:
MDKDevelopers
1 Solution
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
C# or VB.Net?  WinForms or WPF?

How are you currently starting the thread?

Quick answer is to use the BackgroundWorker() control instead thus giving you the RunWorkerCompleted() event along with cancellation ability and even progress updates.
0
 
MDKDevelopersAuthor Commented:
I'm using C# and WinForms.  The thread launches using the Task.Factory.StarNew() syntach, check the below snippet.

Do you know any pros and cons using the BackgroundWorker vs. the way I'm trying to do it?
public CancellationTokenSource tokenSource2 = new CancellationTokenSource();
 CancellationToken ct = tokenSource2.Token;
        
           var task = Task.Factory.StartNew(() => LongRunningProcess(ct));

Open in new window

0
 
Kyle AbrahamsSenior .Net DeveloperCommented:
http://vbcity.com/forums/t/109053.aspx

You can use a callback to invoke the UI thread.
0
NFR key for Veeam Agent for Linux

Veeam is happy to provide a free NFR license for one year.  It allows for the non‑production use and valid for five workstations and two servers. Veeam Agent for Linux is a simple backup tool for your Linux installations, both on‑premises and in the public cloud.

 
avarmaavarmaCommented:
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.
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;
  }

}

Open in new window

0
 
SriVaddadiCommented:
I guess the purpose of having CancellationToken is different. If you want to the know just the status then you should use the Task.Status against TaskStatus.RanToCompletion

if (Task.Status == TaskStatus.RanToCompletion)
0
 
SriVaddadiCommented:
Also if you want to block your main thread until the task is complete, you could use Task.ContinueWith
0
 
MDKDevelopersAuthor Commented:
Hi avarmaavarma,

Great suggestion and example. One question, when I'm handing the RunWorkerCompleted, how do I know if the worker process has been cancelled by the user or completed by it's own. Am I missing something?
0
 
MDKDevelopersAuthor Commented:
avarmaavarma,

I found a work around, I just set a flag based on what happens in the longrunningprocess, but is that the appropriate way?
0
 
MDKDevelopersAuthor Commented:
Great solution, got my answer quickly and solved my problem.
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now