Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should asynchronous delegates use a Callback pattern?

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

like image 562
AspOnMyNet Avatar asked May 13 '26 01:05

AspOnMyNet


1 Answers

  • 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.

like image 182
Brian Avatar answered May 15 '26 15:05

Brian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!