Solved

How to monitor if a Thread completed?

Posted on 2010-08-26
9
725 Views
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.
0
Comment
Question by:MDKDevelopers
[X]
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
9 Comments
 
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.
0
 

Author Comment

by:MDKDevelopers
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

0
 
LVL 40

Expert Comment

by:Kyle Abrahams
ID: 33536213
http://vbcity.com/forums/t/109053.aspx

You can use a callback to invoke the UI thread.
0
The Orion Papers

Are you interested in becoming an AWS Certified Solutions Architect?

Discover a new interactive way of training for the exam.

 
LVL 4

Accepted Solution

by:
avarmaavarma earned 500 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:

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

}

Open in new window

0
 
LVL 16

Expert Comment

by:SriVaddadi
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)
0
 
LVL 16

Expert Comment

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

Author Comment

by:MDKDevelopers
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?
0
 

Author Comment

by:MDKDevelopers
ID: 33542146
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
 

Author Closing Comment

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

Featured Post

The Orion Papers

Are you interested in becoming an AWS Certified Solutions Architect?

Discover a new interactive way of training for the exam.

Question has a verified solution.

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

Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
Ever wonder how to "do" object oriented programming (OOP)?
NetCrunch network monitor is a highly extensive platform for network monitoring and alert generation. In this video you'll see a live demo of NetCrunch with most notable features explained in a walk-through manner. You'll also get to know the philos…
Do you want to know how to make a graph with Microsoft Access? First, create a query with the data for the chart. Then make a blank form and add a chart control. This video also shows how to change what data is displayed on the graph as well as form…

717 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