What is the proper technique to have ThreadA signal ThreadB of some event, without having ThreadB sit blocked waiting for an event to happen?
i have a background thread that will be filling a shared List<T>. i'm trying to find a way to asynchronously signal the "main" thread that there is data available to be picked up.
i considered setting an event with an EventWaitHandle object, but i can't have my main thread sitting at an Event.WaitOne().
i considered having a delegate callback, but a) i don't want the main thread doing work in the delegate: the thread needs to get back to work adding more stuff - i don't want it waiting while the delegate executes, and b) the delegate needs to be marshalled onto the main thread, but i'm not running a UI, i have no Control to .Invoke the delegate against.
i considered have a delegate callback that simply starts a zero interval System.Windows.Forms.Timer (with thread access to the timer synchronized). This way the thread only needs to be stuck as it calls
Timer.Enabled = true;
but that seems like a hack.
In the olden days my object would have created a hidden window and had the thread post messages to that hidden windows' HWND. i considered creating a hidden control, but i gather that you cannot .Invoke on a control with no handle created. Plus, i have no UI: my object could have been created on a web-server, service, or console, i don't want there to be a graphical control appearing - nor do i want to compile a dependency on System.Windows.Forms.
i considered having my object expose an ISynchronizeInvoke interface, but then i would need to implement .Invoke(), and that's my problem.
What is the proper technique to have thread A signal thread B of some event, without having thread B sit blocked waiting for an event to happen?
The BackgroundWorker class is answer in this case. It is the only threading construct that is able to asynchronously send messages to the thread that created the BackgroundWorker object. Internally
BackgroundWorker
uses theAsyncOperation
class by calling theasyncOperation.Post()
method.A few other classes in the .NET framework also use AsyncOperation: