[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
?
Solved

How to monitor if a Thread completed?

Posted on 2010-08-26
9
Medium Priority
?
727 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 41

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
Fill in the form and get your FREE NFR key NOW!

Veeam® is happy to provide a FREE NFR server license to certified engineers, trainers, and bloggers.  It allows for the non‑production use of Veeam Agent for Microsoft Windows. This license is valid for five workstations and two servers.

 
LVL 4

Accepted Solution

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

 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

On Demand Webinar: Networking for the Cloud Era

Ready to improve network connectivity? Watch this webinar to learn how SD-WANs and a one-click instant connect tool can boost provisions, deployment, and management of your cloud connection.

Question has a verified solution.

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

Ever wonder how to "do" object oriented programming (OOP)?
Introduction A frequently used term in Object-Oriented design is "SOLID" which is a mnemonic acronym that covers five principles of OO design.  These principles do not stand alone; there is interplay among them.  And they are not laws, merely princ…
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 …
In this video, Percona Solutions Engineer Barrett Chambers discusses some of the basic syntax differences between MySQL and MongoDB. To learn more check out our webinar on MongoDB administration for MySQL DBA: https://www.percona.com/resources/we…

656 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