{"id":5481,"date":"2022-08-29T00:48:42","date_gmt":"2022-08-28T19:18:42","guid":{"rendered":"https:\/\/jassweb.com\/solved\/solved-why-is-the-windows-forms-ui-blocked-when-executing-task-with-continuewith\/"},"modified":"2022-08-29T00:48:42","modified_gmt":"2022-08-28T19:18:42","slug":"solved-why-is-the-windows-forms-ui-blocked-when-executing-task-with-continuewith","status":"publish","type":"post","link":"https:\/\/jassweb.com\/solved\/solved-why-is-the-windows-forms-ui-blocked-when-executing-task-with-continuewith\/","title":{"rendered":"[Solved] Why is the Windows Forms UI blocked when executing Task with ContinueWith?"},"content":{"rendered":"<p> [ad_1]<br \/>\n<\/p>\n<div id=\"answer-48681904\" class=\"answer js-answer accepted-answer js-accepted-answer\" data-answerid=\"48681904\" data-parentid=\"48681248\" 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>Since you already create (and save) your tasks, the easiest fix would be to await them for each iteration of your while loop:<\/p>\n<pre><code>while (run)\n{\n    action2();\n\n    foreach (Task t in continutask)\n        await t;\n}\n<\/code><\/pre>\n<p>That way, when all pings completed (successful or not) you start the entire process again &#8211; without delay.<\/p>\n<p>One more thing: You could add a <code>textBox1.ScrollToEnd();<\/code> to <code>PrintResult<\/code><\/p>\n<hr>\n<p>Since there is a lot of room for improvement, below is a rewritten and simplified example. I&#8217;ve removed a lot of unused variables (e.g. <code>seqnum<\/code>) and made the <code>PingStart<\/code> method completely asynchronous. I also replaced your ListBox with a TextBox for easier testing, so you might want to revert that in your code.<\/p>\n<p>This still isn&#8217;t the <em>cleanest<\/em> of all possible implementations (mainly because of the global <code>run<\/code>) but it should show you how to do things <em>&#8220;more async&#8221;<\/em> \ud83d\ude42<\/p>\n<pre><code>private async void buttonStart_Click(object sender, EventArgs e)\n{\n    \/\/ If the ping loops are already running, don't start them again\n    if (run)\n        return;\n\n    run = true;\n\n    \/\/ Get all IPs (in my case from a TextBox instead of a ListBox\n    string[] ips = txtIPs.Text.Split(new[] {\"\\r\\n\"}, StringSplitOptions.RemoveEmptyEntries);\n\n    \/\/ Create an array to store all Tasks\n    Task[] pingTasks = new Task[ips.Length];\n\n    \/\/ Loop through all IPs\n    for(int i = 0; i &lt; ips.Length; i++)\n    {\n        string ip = ips[i];\n\n        \/\/ Launch and store a task for each IP\n        pingTasks[i] = Task.Run(async () =&gt;\n            {\n                \/\/ while run is true, ping over and over again\n                while (run)\n                {\n                    \/\/ Ping IP and wait for result (instead of storing it an a global array)\n                    var result = await PingStart(ip);\n\n                    \/\/ Print the result (here I removed seqnum)\n                    PrintResult(result.Item2);\n\n                    \/\/ This line is optional. \n                    \/\/ If you want to blast pings without delay, \n                    \/\/ you can remove it\n                    await Task.Delay(1000);\n                }\n            }\n        );\n    }\n\n    \/\/ Wait for all loops to end after setting run = false.\n    \/\/ You could add a mechanism to call isPing.SendAsyncCancel() instead of waiting after setting run = false\n    foreach (Task pingTask in pingTasks)\n        await pingTask;\n}\n\n\/\/ (very) simplified explanation of changes:\n\/\/ async = this method is async (and therefore awaitable)\n\/\/ Task&lt;&gt; = This async method returns a result of type ...\n\/\/ Tuple&lt;bool, string&gt; = A generic combination of a bool and a string\n\/\/ (-)int seqnum = wasn't used so I removed it\nprivate async Task&lt;Tuple&lt;bool, string&gt;&gt; PingStart(string ip)\n{\n    Ping isPing = new Ping();\n    const int timeout = 2000;\n    const string data = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";\n    var buffer = Encoding.ASCII.GetBytes(data);\n    PingOptions options = new PingOptions {DontFragment = false};\n\n    \/\/ await SendPingAsync = Ping and wait without blocking\n    PingReply reply = await isPing.SendPingAsync(ip, timeout, buffer, options);\n    string rtt = reply.RoundtripTime.ToString();\n\n    bool success = reply.Status == IPStatus.Success;\n    string text;\n\n    if (success)\n    {\n        text = $\"{ip}\" + \" Success!\" + $\" rtt: [{rtt}]\" + $\"Thread: {Thread.CurrentThread.GetHashCode()} Is pool thread: {Thread.CurrentThread.IsThreadPoolThread}\";\n    }\n    else\n    {\n        text = $\"{ip}\" + $\" Not Successful! Status: {reply.Status}\" + $\"Thread: {Thread.CurrentThread.GetHashCode()} Is pool thread: {Thread.CurrentThread.IsThreadPoolThread}\";\n    }\n\n    \/\/ return if the ping was successful and the status message\n    return new Tuple&lt;bool, string&gt;(success, text);\n}\n<\/code><\/pre>\n<p>This way you will have a loop for each IP that will continue independently of each other until <code>run<\/code> is set to <code>false<\/code>.<\/p>\n<\/p><\/div>\n<div class=\"mt24\"><\/div>\n<\/div>\n<p>            <span class=\"d-none\" itemprop=\"commentCount\">8<\/span> <\/p><\/div>\n<\/div>\n<p>[ad_2]<\/p>\n<p>solved Why is the Windows Forms UI blocked when executing Task with ContinueWith? <\/p>\n","protected":false},"excerpt":{"rendered":"<p>[ad_1] Since you already create (and save) your tasks, the easiest fix would be to await them for each iteration of your while loop: while (run) { action2(); foreach (Task t in continutask) await t; } That way, when all pings completed (successful or not) you start the entire process again &#8211; without delay. One &#8230; <a title=\"[Solved] Why is the Windows Forms UI blocked when executing Task with ContinueWith?\" class=\"read-more\" href=\"https:\/\/jassweb.com\/solved\/solved-why-is-the-windows-forms-ui-blocked-when-executing-task-with-continuewith\/\" aria-label=\"More on [Solved] Why is the Windows Forms UI blocked when executing Task with ContinueWith?\">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":[1395,324,1396,1394,959],"class_list":["post-5481","post","type-post","status-publish","format-standard","hentry","category-solved","tag-blocked","tag-c","tag-continuewith","tag-task-parallel-library","tag-winforms"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.4 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>[Solved] Why is the Windows Forms UI blocked when executing Task with ContinueWith? - 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-is-the-windows-forms-ui-blocked-when-executing-task-with-continuewith\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"[Solved] Why is the Windows Forms UI blocked when executing Task with ContinueWith? - JassWeb\" \/>\n<meta property=\"og:description\" content=\"[ad_1] Since you already create (and save) your tasks, the easiest fix would be to await them for each iteration of your while loop: while (run) { action2(); foreach (Task t in continutask) await t; } That way, when all pings completed (successful or not) you start the entire process again &#8211; without delay. One ... Read more\" \/>\n<meta property=\"og:url\" content=\"https:\/\/jassweb.com\/solved\/solved-why-is-the-windows-forms-ui-blocked-when-executing-task-with-continuewith\/\" \/>\n<meta property=\"og:site_name\" content=\"JassWeb\" \/>\n<meta property=\"article:published_time\" content=\"2022-08-28T19:18:42+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-is-the-windows-forms-ui-blocked-when-executing-task-with-continuewith\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/solved-why-is-the-windows-forms-ui-blocked-when-executing-task-with-continuewith\\\/\"},\"author\":{\"name\":\"Kirat\",\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/#\\\/schema\\\/person\\\/65c9c7b7958150c0dc8371fa35dd7c31\"},\"headline\":\"[Solved] Why is the Windows Forms UI blocked when executing Task with ContinueWith?\",\"datePublished\":\"2022-08-28T19:18:42+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/solved-why-is-the-windows-forms-ui-blocked-when-executing-task-with-continuewith\\\/\"},\"wordCount\":177,\"publisher\":{\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/#organization\"},\"keywords\":[\"blocked\",\"c++\",\"continuewith\",\"task-parallel-library\",\"winforms\"],\"articleSection\":[\"Solved\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/solved-why-is-the-windows-forms-ui-blocked-when-executing-task-with-continuewith\\\/\",\"url\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/solved-why-is-the-windows-forms-ui-blocked-when-executing-task-with-continuewith\\\/\",\"name\":\"[Solved] Why is the Windows Forms UI blocked when executing Task with ContinueWith? - JassWeb\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/#website\"},\"datePublished\":\"2022-08-28T19:18:42+00:00\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/solved-why-is-the-windows-forms-ui-blocked-when-executing-task-with-continuewith\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/jassweb.com\\\/solved\\\/solved-why-is-the-windows-forms-ui-blocked-when-executing-task-with-continuewith\\\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/solved-why-is-the-windows-forms-ui-blocked-when-executing-task-with-continuewith\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"[Solved] Why is the Windows Forms UI blocked when executing Task with ContinueWith?\"}]},{\"@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\\\/wp-content\\\/litespeed\\\/avatar\\\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1777008400\",\"url\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/wp-content\\\/litespeed\\\/avatar\\\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1777008400\",\"contentUrl\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/wp-content\\\/litespeed\\\/avatar\\\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1777008400\",\"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 is the Windows Forms UI blocked when executing Task with ContinueWith? - 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-is-the-windows-forms-ui-blocked-when-executing-task-with-continuewith\/","og_locale":"en_US","og_type":"article","og_title":"[Solved] Why is the Windows Forms UI blocked when executing Task with ContinueWith? - JassWeb","og_description":"[ad_1] Since you already create (and save) your tasks, the easiest fix would be to await them for each iteration of your while loop: while (run) { action2(); foreach (Task t in continutask) await t; } That way, when all pings completed (successful or not) you start the entire process again &#8211; without delay. One ... Read more","og_url":"https:\/\/jassweb.com\/solved\/solved-why-is-the-windows-forms-ui-blocked-when-executing-task-with-continuewith\/","og_site_name":"JassWeb","article_published_time":"2022-08-28T19:18:42+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-is-the-windows-forms-ui-blocked-when-executing-task-with-continuewith\/#article","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/solved-why-is-the-windows-forms-ui-blocked-when-executing-task-with-continuewith\/"},"author":{"name":"Kirat","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31"},"headline":"[Solved] Why is the Windows Forms UI blocked when executing Task with ContinueWith?","datePublished":"2022-08-28T19:18:42+00:00","mainEntityOfPage":{"@id":"https:\/\/jassweb.com\/solved\/solved-why-is-the-windows-forms-ui-blocked-when-executing-task-with-continuewith\/"},"wordCount":177,"publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"keywords":["blocked","c++","continuewith","task-parallel-library","winforms"],"articleSection":["Solved"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/jassweb.com\/solved\/solved-why-is-the-windows-forms-ui-blocked-when-executing-task-with-continuewith\/","url":"https:\/\/jassweb.com\/solved\/solved-why-is-the-windows-forms-ui-blocked-when-executing-task-with-continuewith\/","name":"[Solved] Why is the Windows Forms UI blocked when executing Task with ContinueWith? - JassWeb","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/#website"},"datePublished":"2022-08-28T19:18:42+00:00","breadcrumb":{"@id":"https:\/\/jassweb.com\/solved\/solved-why-is-the-windows-forms-ui-blocked-when-executing-task-with-continuewith\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/jassweb.com\/solved\/solved-why-is-the-windows-forms-ui-blocked-when-executing-task-with-continuewith\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/jassweb.com\/solved\/solved-why-is-the-windows-forms-ui-blocked-when-executing-task-with-continuewith\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/jassweb.com\/solved\/"},{"@type":"ListItem","position":2,"name":"[Solved] Why is the Windows Forms UI blocked when executing Task with ContinueWith?"}]},{"@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\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1777008400","url":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1777008400","contentUrl":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1777008400","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\/5481","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=5481"}],"version-history":[{"count":0,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/5481\/revisions"}],"wp:attachment":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/media?parent=5481"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/categories?post=5481"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/tags?post=5481"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}