Skip to content

Multithreading in WPF: getting started

As it’s common for Java GUI frameworks, only main thread should access GUI objects (see respective MSDN article). Alright, real requirement is a bit weaker: Only the thread that the Dispatcher was created on may access the DispatcherObject directly. Effectively same, just keep it in mind.

First thing to know

From other threads, to call main one, do:

    invokedMethodDelegate, parameters);

Know that all the BeginInvoke()s go through ThreadPool. .NET’s ThreadPool is static utility class, with a single task queue for everything.

Which means client call can freeze all the application, including WPF internal tasks.

Can you think of any reason to do so? I can’t. It’s another “we’ll never know“.

If you need a thread pool, I recommend a SmartThreadPool by Ami Bar. It can be instantiated, so different pools of tasks won’t clash with each other.

Second thing

Read Kent Boogaart’s post about binding to collections. Modifying or even iterating a collection across threads needs some workarounds, if you can’t afford to lock it entirely. Kent’s .NET blog is worth reading anyway.

One more little thing

is: unhandled exceptions go to <Application DispatcherUnhandledException=”your handler”>. You didn’t expect main thread to handle them, right? Especially as there is no Main() function… Oh, once I missed that too. So, have a proper handler in each function you start as a thread.

Current “to-reads” are:

Sorry if this looks more like a linkdump; will update when I get more into this. I know I will…

Post a Comment

Your email is never published nor shared.