Solved

How to monitor if a Thread completed?

Posted on 2010-08-26
9
721 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
9 Comments
 
LVL 85

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
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

 
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

Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

Question has a verified solution.

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

A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
Introduction This article explores the design of a cache system that can improve the performance of a web site or web application.  The assumption is that the web site has many more “read” operations than “write” operations (this is commonly the ca…
In a recent question (https://www.experts-exchange.com/questions/28997919/Pagination-in-Adobe-Acrobat.html) here at Experts Exchange, a member asked how to add page numbers to a PDF file using Adobe Acrobat XI Pro. This short video Micro Tutorial sh…
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

776 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