看板 C_Sharp 關於我們 聯絡資訊
最近在實作進度條更新 在網上也看了一些範例 但輪到自己實作時卻卡住了 環境VS2005 執行緒應該有進入更新 但卻像卡在for迴圈的地方 然後才進行更新 實在想不出為什麼了 https://www.dropbox.com/s/pu8tyqt2otm723u/WindowsApplication1.zip?dl=0 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Threading; namespace WindowsApplication1 { public partial class Form1 : Form { int m_all = 0; int max = 300; Thread t = null; public Form1() { InitializeComponent(); t = new Thread(new ThreadStart(threadwork)); } private void button1_Click(object sender, EventArgs e) { m_all = 0; t.Start(); //無腦迴圈 for (m_all = 0; m_all < max; m_all++) { for (int j = 0; j < 1000; j++) for (int k = 0; k < 10000; k++) int m = j + k; } } delegate void SetUpdate(); void threadwork() { if (progressBar1.InvokeRequired) { SetUpdate d = new SetUpdate(threadwork); progressBar1.Invoke(d, new object[] { }); } else { while (true) { double value = 1.0 * Convert.ToDouble(m_all) / max * 100; progressBar1.Value = Convert.ToInt32(value); progressBar1.Refresh(); if (m_all >= max) { break; } } } } } -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 211.20.98.14 ※ 文章網址: https://www.ptt.cc/bbs/C_Sharp/M.1435121678.A.892.html
honoYang: 自己解答一下 不確定有無錯 因為UI不一定會即時更新 06/25 23:55
honoYang: 所以要在忙碌的地方(for迴圈內)加入application.doevent 06/25 23:56
honoYang: 更新UI 06/25 23:56
honoYang: google 關鍵字 C# UI響應 thread 06/25 23:57
FancyWing: 應該說,UI thread 被 button1_click 卡住了,因此 06/27 17:03
FancyWing: t thread 就算有更新資料,但 btn1_click 沒有 release 06/27 17:04
FancyWing: UI 會不更新,因此已知問題,加入 app.do~ 可以讓 06/27 17:05
FancyWing: UI thread 跳出去處理 其他 UI thread 的事件 06/27 17:06
FancyWing: 漏說了,如果 processBar1 跟 btn1 不屬於同一個thread 06/27 17:07
FancyWing: 是不會發生這樣事情的,不過 會造成 processBar 沒跑完 06/27 17:08
FancyWing: 但主UI已經可以被操作了 06/27 17:09
FancyWing: 把無腦迴圈那邊也丟另一個 thread同樣可以解掉更新問提 06/27 17:10
disabledman: keyword: invoke doevent 07/17 17:53