[C#] .Net Core WPF UI 不要被 hang 住,更新 UI

2019-12-23

最近在寫一點東西,因為太久沒有寫了,有點小生疏,因為我要跟網路大量的溝通,但是跟網路溝通的時候 UI 會被 hang 住,會等到連續操作完之後,UI 才會一次更新,這樣感覺很詭異,所以找了一些方法,目前這比較簡單而且成功..筆記一下



這邊我跑十次迴圈,每一次,我都去兩個網站把原始碼拿回來,顯示在  TextBox 裡面,每一個動作我都用  Application.Current.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Background, new System.Threading.ThreadStart(delegate 去更新 UI

Full Source Code :

for (var i = 1; i <= 10; i++) { //-- yahoo Application.Current.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Background, new System.Threading.ThreadStart(delegate { txtLog.Text += "第" + i + "次擷取網站..\r\n\r\n"; txtLog.Text += "擷取第一個網站\r\n"; txtLog.ScrollToEnd(); })); WebClient webClient1 = new WebClient(); webClient1.Encoding = System.Text.Encoding.UTF8; webClient1.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"); byte[] byteRes1 = webClient1.DownloadData("http://tw.yahoo.com"); string res1 = System.Text.Encoding.UTF8.GetString(byteRes1); Application.Current.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Background, new System.Threading.ThreadStart(delegate { txtLog.Text += res1 + "\r\n"; txtLog.ScrollToEnd(); })); //--bing Application.Current.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Background, new System.Threading.ThreadStart(delegate { txtLog.Text += "擷取第二個網站\r\n"; txtLog.ScrollToEnd(); })); byte[] byteRes2 = webClient1.DownloadData("http://www.bing.com"); webClient1.Encoding = System.Text.Encoding.UTF8; string res2 = System.Text.Encoding.UTF8.GetString(byteRes2); Application.Current.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Background, new System.Threading.ThreadStart(delegate { txtLog.Text += res2 + "\r\n"; txtLog.ScrollToEnd(); })); System.Threading.Thread.Sleep(1000); }

關鍵是這一段:

Source Code :
Application.Current.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Background, new System.Threading.ThreadStart(delegate { txtLog.Text +="...."; txtLog.ScrollToEnd(); }));

網路上有看到做法很多,但是效果不是我預期的,這邊就分享一下,順便自己筆記一下..
因為現在 .net Core 3.1 都出了,所以現在範例基本上我都是用 .net Core WPF 去撰寫

reference :
https://stackoverflow.com/questions/7959005/update-ui-from-background-thread/28563279#28563279


當麻許的碎念筆記 2014 | Donma Hsu Design.