I vaguely recall that WinAPI provided something called APC which allowed you to instruct a thread to execute a function on your behalf and it would do so, as soon as it found the time to do it. The thread would not need to wait on a signal but the kernel maintained the APC queue for it and instructed the thread to execute the items in the queue.
I did some research how this would be done in .NET but so far I have not found a way to do this. I know about BeginInvoke but this is only applicable in the context of UI controls, I believe?
How would I go about doing this in the .NET environment?
Thank you!
This is exposed somewhat in .NET, in the very specific case of APCs being used for I/O completion callbacks. Which is a very common use for APCs. It is quite low-level, as APCs are, a core method is ThreadPool.BindHandle() which sets up the plumbing to allow the callback to execute managed code on a threadpool thread. Making the calls to start the overlapped I/O is however not, that’s up to you to pinvoke. This is otherwise already ably wrapped by the various classes that perform I/O and their BeginXxxx() methods, like FileStream, PipeStream, Socket, etcetera.
Next thing you need for your own APCs is putting a thread in an alertable wait-state, equivalent to WaitForSingleObjectEx() with a TRUE value for the bAlertable argument. That’s heavily wrapped by the CLR, it has a big stake in the alertable state for waits since that matters a great deal whether or not managed threads can be safely aborted. Afaik, all waits that you call in managed code are alertable, including methods like Thread.Join() and Thread.Sleep(). Ignore the bool argument named “exitContext” in the WaitHandle.WaitXxx overloads, that means something else.