Posts

Showing posts from May, 2018

Windows message pumb / Dispatcher / RealProxy

Not so long ago I had to integrate a COM component into an application. The catch was the application had no Windows message pumb and the COM component uses exactly this message pumb for some communications. So I need to create a thread with its own message pumb and then dispatch the calls to the component to the thread holding this message pumb. Creating a thread is simple and quickly done. _thread = new Thread(RunThread) { Name = nameof(MessagePumpDispatcher), IsBackground = true } _thread.SetApartmentState(ApartmentState.STA); _thread.Start(); And to start a new message pumb I can use the Dispatcher type. _dispatcher = Dispatcher.CurrentDispatcher; try { Dispatcher.Run(); } catch (ThreadAbortException) { Thread.ResetAbort(); } Dispatching work to this thread can be achieved by using the Invoke method on the Dispatcher. _dispatcher.Invoke(action); This is the whole class. Now to send all calls of the component to the correct class I could either wrap

Components of Tasks & Threading in .NET

Image
I recommend understanding the basics of async and await before you read this article. This is a good introduction from Stephen Cleary. As you might know simply using async and await doesn't mean your code is executed on different threads. To achieve this you must use Task.Run , TaskFactory.StartNew or the Task Parallel Library . This is an introduction in the different components at play when you want to schedule tasks on different threads. TaskFactory The TaskFactory is a simple container where you can configure options for the creation and continuation of Tasks. Furthermore you can specify an canncelation Token which will be used by all Tasks created through this factory. And lastly you can define your own TaskScheduler. It's your choise if you want to use a TaskFactory to start a new task or if you want to start a task directly trough Task.Run. MSDN TaskFactory TaskScheduler The TaskScheduler is responsible to run the next task on the correct