Search code examples
c#multithreadingdispatcher

Problems with dispatcher in C# console application


I need to invoke method runed on timer thread on right working thread. Invoke/BeginInvoke process is working for me. There are 2 threads which shares one inter thread data container for data exchange. One is filling queue, one shuld process the queue. Queue raises event if it is filled after empty state. All the problem is caused by timer, which open new thread on its elapsed event. I am using Dispatcher to dispatch on the right thread, but everything works, except this Dispatcher. :-)

Please, does anybody see where the problem is?

Complete test code is here: http://pastebin.com/jqYbR9PS.

Debug output is this:

App Thread ID: 9
Processor Thread ID: 10
Processor Dispatcher Thread ID: 10
The thread '<No Name>' (0x888) has exited with code 0 (0x0).
Processor QueueListener caller Thread ID: 12
Processor Dispatcher Thread ID: 10
Processor invoking ProcessQueue.
...here shut be processing output...
Processor invoked ProcessQueue.
App Thread ID on end: 9
The thread 'vshost.RunParkingWindow' (0x17c4) has exited with code 0 (0x0).
The thread '<No Name>' (0x820) has exited with code 0 (0x0).
The program '[5760] TestingConsoleApplication.vshost.exe: Managed (v4.0.30319)' has exited with code 0 (0x0).

ProcessQueue is never called/invoked.

Thank you.


Solution

  • You need to actually start the dispatcher by calling Dispatcher.Run() for the dispatcher to process the calls invoked to it.

    It's pretty strange to use a Dispatcher from a console application - the Dispatcher is used for WPF applications but I guess it will work.

    Note that the call to Dispatcher.Run() won't return - it will enter a loop until you call Dispatcher.BeginInvokeShutdown()

    See this blog post for an example.