
{"id":833,"date":"2011-06-27T21:39:16","date_gmt":"2011-06-28T01:39:16","guid":{"rendered":"http:\/\/www.ikriv.com\/blog\/?p=833"},"modified":"2011-06-27T21:39:16","modified_gmt":"2011-06-28T01:39:16","slug":"backgroundworker-and-ui-threads","status":"publish","type":"post","link":"https:\/\/ikriv.com\/blog\/?p=833","title":{"rendered":"BackgroundWorker and UI threads"},"content":{"rendered":"<p>Popular belief (reinforced indirectly by MSDN) is that <code>BackgroundWorker<\/code> class will marshal the &#8220;progress&#8221; and &#8220;completed&#8221; events back to the calling thread. This turned out to be most certainly not true. A more restricted (and closer to reality) form of this belief is that if <code>BackgroundWorker<\/code> is spawned by a WPF UI thread, the events will be marshaled back to the UI thread. This is almost true. Read on.<\/p>\n<p><code>BackgroundWorker<\/code> uses <code>SynchronizationContext.Post()<\/code> to marshal progress and completed events. It captures the synchronization context of the current thread when you invoke <code>RunorkerAsync()<\/code> method. If current thread has no synchronization context, a default one will be created.<\/p>\n<p>For WPF UI threads the synchronization context (of type <code>DispatcherSynchronizationContext<\/code>)  will indeed post the events back to the UI thread.<\/p>\n<table border=\"1\" cellpadding=\"5\">\n<tr>\n<td>UI thread<\/td>\n<td><code>RunWorkerAsync()<\/code><\/td>\n<\/tr>\n<tr>\n<td>Thread pool thread<\/td>\n<td><code>DoWork()<\/code><\/td>\n<\/tr>\n<tr>\n<td>UI thread<\/td>\n<td><code>RunWorkerCompleted<\/code> and <code>ProgressChanged<\/code> events<\/td>\n<\/tr>\n<\/table>\n<p>In background thread, or in main thread of a console application the synchronization context will schedule event calls on a thread pool. So, typically you will end up with 3 or more threads:<\/p>\n<table border=\"1\" cellpadding=\"5\">\n<tr>\n<td>Calling thread<\/td>\n<td><code>RunWorkerAsync()<\/code><\/td>\n<\/tr>\n<tr>\n<td>Thread pool thread #1<\/td>\n<td><code>DoWork()<\/code><\/td>\n<\/tr>\n<tr>\n<td>Thread pool thread #2&#8230;n<\/td>\n<td><code>RunWorkerCompleted<\/code> and <code>ProgressChanged<\/code> events<\/td>\n<\/tr>\n<\/table>\n<p>An interesting twist occurs if you run <code>BackgroundWorker<\/code> on a soon-to-be-come-UI-thread thread. Typically it&#8217;s a main thread of your application before you called <code>Application.Run()<\/code>. Windows is not psychic, and it does not know what you are about to do. So, until you actually started a WPF application, your main thread is considered a regular thread, and default synchronization context will be used instead of <code>DispatcherSynchronizationContext<\/code>. Thus, your background worker events <b>will not<\/b> be marshalled back to the UI thread. Instead, they will be executed on a thread pool. If you touch UI in those callbacks, bad things will happen.<\/p>\n<p>The workarounds are:<br \/>\n&#8211; don&#8217;t use background workers before <code>Application.Run()<\/code><br \/>\n&#8211; use <code>Dispatcher.BeginInvoke()<\/code> inside suspect callbacks (however be prepared that proponents of the myth may remove them as redundant)<br \/>\n&#8211; manually install <code>DispatcherSynchronizationContext<\/code> (don&#8217;t do this it at home; I did not try it, but I think it should work).<br \/>\n<a style=\"display:none\" href=\"http:\/\/www.codeproject.com\/script\/Articles\/BlogFeedList.aspx?amid=1181663\" rel=\"tag\">CodeProject<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Popular belief (reinforced indirectly by MSDN) is that BackgroundWorker class will marshal the &#8220;progress&#8221; and &#8220;completed&#8221; events back to the calling thread. This turned out to be most certainly not <a href=\"https:\/\/ikriv.com\/blog\/?p=833\" class=\"more-link\">[&hellip;]<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"Layout":"","footnotes":""},"categories":[3,4],"tags":[],"class_list":["entry","author-ikriv","post-833","post","type-post","status-publish","format-standard","category-dotnet","category-hack"],"_links":{"self":[{"href":"https:\/\/ikriv.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/833","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/ikriv.com\/blog\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/ikriv.com\/blog\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/ikriv.com\/blog\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/ikriv.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=833"}],"version-history":[{"count":0,"href":"https:\/\/ikriv.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/833\/revisions"}],"wp:attachment":[{"href":"https:\/\/ikriv.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=833"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/ikriv.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=833"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/ikriv.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=833"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}