views:

243

answers:

2

One of the patterns used with asynchronous delegates is also a Callback pattern, where initial thread ( one that called BeginInvoke ) T1 continues without waiting or checking whether the spawned thread T2 has completed. Instead, when T2 has completed, the T2 calls callback method, which handles the results, calls EndInvoke and informs the T1 that the task is finished.

a) If callback method is supposed to inform T1 when the task is finished, then why isn’t this callback method called inside T1 and not T2?

2) Is there some standard pattern how callback method should inform T1 that T2 has finished?

3) Should Callback pattern be used even when T1 needs to receive the returned value of asynchronously called method?

thanx

+3  A: 
  • why isn't the callback method called in T1?

Generally this is impossible; if T1 is off doing some other work, there's no way to marshall work back to it, unless the thread already has a mechanism for posting and scheduleing work on it (e.g. the UI thread, via a SynchronizationContext).

  • is there a standard pattern for cross-thread notification?

I would say no; there are a number of cross-thread synchronization patterns that each apply to different targeted scenarios.

  • what if T1 needs return value?

If T1 needs the return value under the current stack, then eventually it is going to have to block to get it. The blocking may happen by calling EndInvoke, using the WaitHandle, or other strategies from the previous bullet.

If the thing that needs the return value is 'just the thread' (e.g. the UI thread) but not under a particular callstack/activation context, then usually SynchronizationContext.Post or Dispatcher.Invoke is used to marshall the work eventually back to the UI thread once it is ready.

Brian
I assume that if T2 needs to inform T1 that it is finished, then implementing callback method ( ie callback pattern) provides no benefits over polling pattern ( where T1 periodically checks via IsCompleted property whether spawned thread has completed ) and thus we should instead implement polling pattern?
AspOnMyNet
+3  A: 

Letting a thread run code in another thread is quite untrivial. But it is a common requirement for Windows Forms and WPF apps, user interface components are never thread-safe. They do have a common pattern for it, respectively the Control.Invoke and the Dispatcher.Invoke methods. And there is a standard helper class, BackgroundWorker. It raises events on the UI thread, it's analogue for the callback method is its RunWorkerCompleted event.

You can certainly spin your own mechanism if you prefer using a delegate's BeginInvoke() method, but getting that right can be tricky.

Hans Passant