2

When using Delegate.BeginInvoke how do I interrogate the delegate to get the status of the asynchronous thread? The status I'm really interested in is determining if the thread has completed execution. Thank you.

The thing I want to avoid is having to block the thread that created the new thread(s) because I don't care about how long these threads take to finish.

Achilles
  • 11,165
  • 9
  • 62
  • 113
  • It's not all that useful to find out the status of the *thread* that the task executes on. `Delegate.BeginInvoke` uses the thread-pool, so the thread that the delegate executes on may well go on to do other things after it is done with it. You are probably interested in the status of the *task* itself. – Ani Jan 03 '11 at 15:14

2 Answers2

1

You can use IAsyncResult.IsCompleted for that.

Victor Haydin
  • 3,518
  • 2
  • 26
  • 41
  • Doesn't this require that the thread that initiates the thread block until the asynchronous thread completes? – Achilles Jan 03 '11 at 14:08
  • No, you don't need to use IAsyncResult from main thread. You can start some long running operation asynchronously, and, for example, create separate thread with timer, which will poll this operation state to show progress on UI. Or run several async operations in parallel and wait while all of them will finished. – Victor Haydin Jan 03 '11 at 14:15
  • I don't see any problem with invoking the asynchronous operation from the main thread either. As long as you are simply polling using the `IAsyncResult.IsComplete` property, your main thread (or invoking thread) should be able to continue without waiting. I believe your code should eventually call `IAsyncResult.EndInvoke`, which is a blocking call, but you could choose to call that only after `IAsyncResult.IsComplete` returns true. – Dr. Wily's Apprentice Jan 03 '11 at 14:23
1

This ties in nicely to your other question regarding calling Delegate.EndInvoke. If you did that, you'd know when your thread had completed. You wouldn't have to block the main thread at all just to check on its status.

Community
  • 1
  • 1
Dave
  • 14,618
  • 13
  • 91
  • 145