{"id":31734,"date":"2023-01-24T05:39:51","date_gmt":"2023-01-24T00:09:51","guid":{"rendered":"https:\/\/jassweb.com\/solved\/solved-why-does-this-causes-the-application-to-hang-closed\/"},"modified":"2023-01-24T05:39:51","modified_gmt":"2023-01-24T00:09:51","slug":"solved-why-does-this-causes-the-application-to-hang-closed","status":"publish","type":"post","link":"https:\/\/jassweb.com\/solved\/solved-why-does-this-causes-the-application-to-hang-closed\/","title":{"rendered":"[Solved] Why does this causes the application to hang [closed]"},"content":{"rendered":"<p> [ad_1]<br \/>\n<\/p>\n<div id=\"answer-27770352\" class=\"answer js-answer accepted-answer js-accepted-answer\" data-answerid=\"27770352\" data-parentid=\"27765299\" data-score=\"1\" data-position-on-page=\"1\" data-highest-scored=\"1\" data-question-has-accepted-highest-score=\"1\" itemprop=\"acceptedAnswer\" itemscope itemtype=\"https:\/\/schema.org\/Answer\">\n<div class=\"post-layout\">\n<div class=\"votecell post-layout--left\"><\/div>\n<div class=\"answercell post-layout--right\">\n<div class=\"s-prose js-post-body\" itemprop=\"text\">\n<p>The biggest problem here is that your constructor does not return until all of the tasks have completed. Until the constructor returns, the window will not be shown, because the window messages related to drawing the window aren&#8217;t going to be processed.<\/p>\n<p>Note that you don&#8217;t really have &#8220;deadlock&#8221; here per se. Instead, if you waited long enough (i.e. until all the tasks have completed), the window would actually be shown.<\/p>\n<p>When you add the call to <code>MessageBox.Show()<\/code>, you give the UI thread a chance to process the window message queue. That is, the normal modal dialog includes a thread message pump which winds up handling those messages in the queue, including those related to showing your window. Note that even if you add the <code>MessageBox.Show()<\/code>, that won&#8217;t result in the window being updated as your processing progresses. It just allows the window to be shown before you block the UI thread again.<\/p>\n<p>One way to address this is to switch to the <code>async<\/code>\/<code>await<\/code> pattern. For example:<\/p>\n<pre><code>public MainWindow()\n{\n    InitializeComponent();\n    var _ = ProcessURLs();\n}\n\npublic async Task ProcessURLs()\n{\n    List&lt;Task&lt;string&gt;&gt; tasks = URLsToProcess.Select(uri =&gt; DownloadStringAsTask(new Uri(uri))).ToList();\n\n    while (tasks.Count &gt; 0)\n    {\n        Task&lt;string&gt; task = await Task.WhenAny(tasks);\n        string messageText;\n\n        if (task.Status == TaskStatus.RanToCompletion)\n        {\n            messageText = string.Format(\"{0} has completed\", task.AsyncState);\n            \/\/ TODO: do something with task.Result, i.e. the actual downloaded text\n        }\n        else\n        {\n            messageText = string.Format(\"{0} has completed with failure: {1}\", task.AsyncState, task.Status);\n        }\n\n        this.tbStatusBar.Text = messageText;\n        tasks.Remove(task);\n    }\n\n    tbStatusBar.Text = \"All tasks completed\";\n}\n<\/code><\/pre>\n<p>I&#8217;ve rewritten the <code>ProcessURLs()<\/code> method as an <code>async<\/code> method. This means that when the constructor calls it, it will run synchronously up to the first <code>await<\/code> statement, at which point it will yield and allow the current thread to continue normally.<\/p>\n<p>When the call to <code>Task.WhenAny()<\/code> completes (i.e. any of the tasks complete), the runtime will resume execution of the <code>ProcessURLs()<\/code> method by invoking the continuation on the UI thread. This allows the method to access the UI objects (e.g. <code>this.tbStatusBar.Text<\/code>) normally, while occupying the UI thread only long enough to process the completion.<\/p>\n<p>When the loop returns to the top and the <code>Task.WhenAny()<\/code> method is called again, the whole sequence is repeated (i.e. just the way a loop is supposed to work \ud83d\ude42 ).<\/p>\n<p>Some other notes:<\/p>\n<ul>\n<li>The <code>var _ =<\/code> bit in the constructor is there to suppress the compiler warning that would otherwise occur when the <code>Task<\/code> return value is ignored.<\/li>\n<li>IMHO, it would be better to not initialize these operations in the constructor. The constructor is just generally a bad place to be doing significant work like this. Instead, I would (for example) override the <code>OnActivated()<\/code> method, making it <code>async<\/code> so you can use the <code>await<\/code> statement with the call to <code>ProcessURLs()<\/code> (i.e. a more idiomatic way to call an <code>async<\/code> method). This ensures the window is completely initialized and shown before you start doing any other processing.<\/li>\n<\/ul>\n<p>In this particular example, starting the processing in the constructor is probably not really going to hurt anything, as long as you&#8217;re using <code>async<\/code>\/<code>await<\/code>, since the UI-related stuff isn&#8217;t going to be able to be executed in any case until at least the constructor has returned. I just try to avoid doing this sort of thing in the constructor as a general rule.<\/p>\n<ul>\n<li>I also modified the general handling of your task collection, to something that I feel is somewhat more suitable. It gets rid of the repeated reinitialization of the <code>tasks<\/code> collection, as well as takes advantage of the semantics of the <code>WhenAny()<\/code> method. I also removed the <code>AsParallel()<\/code>; given that the long-running part of the processing is handled asynchronously already, there did not seem to be any advantage in the attempt to parallelize the <code>Select()<\/code> itself.<\/li>\n<\/ul>\n<\/div>\n<div class=\"mt24\"><\/div>\n<\/div>\n<p>            <span class=\"d-none\" itemprop=\"commentCount\">2<\/span> <\/p><\/div>\n<\/div>\n<p>[ad_2]<\/p>\n<p>solved Why does this causes the application to hang [closed] <\/p>\n","protected":false},"excerpt":{"rendered":"<p>[ad_1] The biggest problem here is that your constructor does not return until all of the tasks have completed. Until the constructor returns, the window will not be shown, because the window messages related to drawing the window aren&#8217;t going to be processed. Note that you don&#8217;t really have &#8220;deadlock&#8221; here per se. Instead, if &#8230; <a title=\"[Solved] Why does this causes the application to hang [closed]\" class=\"read-more\" href=\"https:\/\/jassweb.com\/solved\/solved-why-does-this-causes-the-application-to-hang-closed\/\" aria-label=\"More on [Solved] Why does this causes the application to hang [closed]\">Read more<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[320],"tags":[352,324,3327,1394,874],"class_list":["post-31734","post","type-post","status-publish","format-standard","hentry","category-solved","tag-net","tag-c","tag-deadlock","tag-task-parallel-library","tag-wpf"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>[Solved] Why does this causes the application to hang [closed] - JassWeb<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/jassweb.com\/solved\/solved-why-does-this-causes-the-application-to-hang-closed\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"[Solved] Why does this causes the application to hang [closed] - JassWeb\" \/>\n<meta property=\"og:description\" content=\"[ad_1] The biggest problem here is that your constructor does not return until all of the tasks have completed. Until the constructor returns, the window will not be shown, because the window messages related to drawing the window aren&#8217;t going to be processed. Note that you don&#8217;t really have &#8220;deadlock&#8221; here per se. Instead, if ... Read more\" \/>\n<meta property=\"og:url\" content=\"https:\/\/jassweb.com\/solved\/solved-why-does-this-causes-the-application-to-hang-closed\/\" \/>\n<meta property=\"og:site_name\" content=\"JassWeb\" \/>\n<meta property=\"article:published_time\" content=\"2023-01-24T00:09:51+00:00\" \/>\n<meta name=\"author\" content=\"Kirat\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Kirat\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-why-does-this-causes-the-application-to-hang-closed\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-why-does-this-causes-the-application-to-hang-closed\/\"},\"author\":{\"name\":\"Kirat\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31\"},\"headline\":\"[Solved] Why does this causes the application to hang [closed]\",\"datePublished\":\"2023-01-24T00:09:51+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-why-does-this-causes-the-application-to-hang-closed\/\"},\"wordCount\":544,\"publisher\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\"},\"keywords\":[\".net\",\"c++\",\"deadlock\",\"task-parallel-library\",\"wpf\"],\"articleSection\":[\"Solved\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-why-does-this-causes-the-application-to-hang-closed\/\",\"url\":\"https:\/\/jassweb.com\/solved\/solved-why-does-this-causes-the-application-to-hang-closed\/\",\"name\":\"[Solved] Why does this causes the application to hang [closed] - JassWeb\",\"isPartOf\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#website\"},\"datePublished\":\"2023-01-24T00:09:51+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-why-does-this-causes-the-application-to-hang-closed\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/jassweb.com\/solved\/solved-why-does-this-causes-the-application-to-hang-closed\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-why-does-this-causes-the-application-to-hang-closed\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/jassweb.com\/solved\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"[Solved] Why does this causes the application to hang [closed]\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/jassweb.com\/solved\/#website\",\"url\":\"https:\/\/jassweb.com\/solved\/\",\"name\":\"JassWeb\",\"description\":\"Build High-quality Websites\",\"publisher\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/jassweb.com\/solved\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\",\"name\":\"Jass Web\",\"url\":\"https:\/\/jassweb.com\/solved\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png\",\"contentUrl\":\"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png\",\"width\":693,\"height\":132,\"caption\":\"Jass Web\"},\"image\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/\"}},{\"@type\":\"Person\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31\",\"name\":\"Kirat\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775798750\",\"contentUrl\":\"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775798750\",\"caption\":\"Kirat\"},\"sameAs\":[\"http:\/\/jassweb.com\"],\"url\":\"https:\/\/jassweb.com\/solved\/author\/jaspritsinghghumangmail-com\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"[Solved] Why does this causes the application to hang [closed] - JassWeb","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/jassweb.com\/solved\/solved-why-does-this-causes-the-application-to-hang-closed\/","og_locale":"en_US","og_type":"article","og_title":"[Solved] Why does this causes the application to hang [closed] - JassWeb","og_description":"[ad_1] The biggest problem here is that your constructor does not return until all of the tasks have completed. Until the constructor returns, the window will not be shown, because the window messages related to drawing the window aren&#8217;t going to be processed. Note that you don&#8217;t really have &#8220;deadlock&#8221; here per se. Instead, if ... Read more","og_url":"https:\/\/jassweb.com\/solved\/solved-why-does-this-causes-the-application-to-hang-closed\/","og_site_name":"JassWeb","article_published_time":"2023-01-24T00:09:51+00:00","author":"Kirat","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Kirat","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/jassweb.com\/solved\/solved-why-does-this-causes-the-application-to-hang-closed\/#article","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/solved-why-does-this-causes-the-application-to-hang-closed\/"},"author":{"name":"Kirat","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31"},"headline":"[Solved] Why does this causes the application to hang [closed]","datePublished":"2023-01-24T00:09:51+00:00","mainEntityOfPage":{"@id":"https:\/\/jassweb.com\/solved\/solved-why-does-this-causes-the-application-to-hang-closed\/"},"wordCount":544,"publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"keywords":[".net","c++","deadlock","task-parallel-library","wpf"],"articleSection":["Solved"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/jassweb.com\/solved\/solved-why-does-this-causes-the-application-to-hang-closed\/","url":"https:\/\/jassweb.com\/solved\/solved-why-does-this-causes-the-application-to-hang-closed\/","name":"[Solved] Why does this causes the application to hang [closed] - JassWeb","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/#website"},"datePublished":"2023-01-24T00:09:51+00:00","breadcrumb":{"@id":"https:\/\/jassweb.com\/solved\/solved-why-does-this-causes-the-application-to-hang-closed\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/jassweb.com\/solved\/solved-why-does-this-causes-the-application-to-hang-closed\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/jassweb.com\/solved\/solved-why-does-this-causes-the-application-to-hang-closed\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/jassweb.com\/solved\/"},{"@type":"ListItem","position":2,"name":"[Solved] Why does this causes the application to hang [closed]"}]},{"@type":"WebSite","@id":"https:\/\/jassweb.com\/solved\/#website","url":"https:\/\/jassweb.com\/solved\/","name":"JassWeb","description":"Build High-quality Websites","publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/jassweb.com\/solved\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/jassweb.com\/solved\/#organization","name":"Jass Web","url":"https:\/\/jassweb.com\/solved\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/","url":"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png","contentUrl":"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png","width":693,"height":132,"caption":"Jass Web"},"image":{"@id":"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/"}},{"@type":"Person","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31","name":"Kirat","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/image\/","url":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775798750","contentUrl":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775798750","caption":"Kirat"},"sameAs":["http:\/\/jassweb.com"],"url":"https:\/\/jassweb.com\/solved\/author\/jaspritsinghghumangmail-com\/"}]}},"_links":{"self":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/31734","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/comments?post=31734"}],"version-history":[{"count":0,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/31734\/revisions"}],"wp:attachment":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/media?parent=31734"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/categories?post=31734"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/tags?post=31734"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}