How to monitor if a Thread completed?

Posted on 2010-08-26
Medium Priority
Last Modified: 2013-11-11
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.
Question by:MDKDevelopers
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 33536134
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.

Author Comment

ID: 33536190
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

LVL 40

Expert Comment

by:Kyle Abrahams
ID: 33536213

You can use a callback to invoke the UI thread.
Veeam Disaster Recovery in Microsoft Azure

Veeam PN for Microsoft Azure is a FREE solution designed to simplify and automate the setup of a DR site in Microsoft Azure using lightweight software-defined networking. It reduces the complexity of VPN deployments and is designed for businesses of ALL sizes.


Accepted Solution

avarmaavarma earned 2000 total points
ID: 33537304
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:

    string s1 = task1.EndInvoke (cookie);
 catch(Exception e)


Open in new window

LVL 16

Expert Comment

ID: 33541788
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)
LVL 16

Expert Comment

ID: 33541814
Also if you want to block your main thread until the task is complete, you could use Task.ContinueWith

Author Comment

ID: 33541847
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?

Author Comment

ID: 33542146

I found a work around, I just set a flag based on what happens in the longrunningprocess, but is that the appropriate way?

Author Closing Comment

ID: 33542162
Great solution, got my answer quickly and solved my problem.

Featured Post


We will be discussing what Azure Stack is, how does it fit into the suit of offerings that Azure has currently, and where can it fit into your organizations technology stack. We will also be discussing limitations of the platform while covering various applicable scenarios.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The Fluent Interface Design Pattern You can use the Fluent Interface (http://en.wikipedia.org/wiki/Fluent_interface) design pattern to make your PHP code easier to read and maintain.  "Fluent Interface" is an object-oriented design pattern that r…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…
In this video, Percona Director of Solution Engineering Jon Tobin discusses the function and features of Percona Server for MongoDB. How Percona can help Percona can help you determine if Percona Server for MongoDB is the right solution for …
Suggested Courses

752 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question