[問題] 執行緒與進度條更新

作者: honoYang (......)   2015-06-24 12:54:34
最近在實作進度條更新
在網上也看了一些範例
但輪到自己實作時卻卡住了
環境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;
}
}
}
}
}
作者: honoYang (......)   2015-06-25 23:55:00
自己解答一下 不確定有無錯 因為UI不一定會即時更新所以要在忙碌的地方(for迴圈內)加入application.doevent更新UIgoogle 關鍵字 C# UI響應 thread
作者: FancyWing (TDiCS)   2015-06-27 17:03:00
應該說,UI thread 被 button1_click 卡住了,因此t thread 就算有更新資料,但 btn1_click 沒有 releaseUI 會不更新,因此已知問題,加入 app.do~ 可以讓UI thread 跳出去處理 其他 UI thread 的事件漏說了,如果 processBar1 跟 btn1 不屬於同一個thread是不會發生這樣事情的,不過 會造成 processBar 沒跑完但主UI已經可以被操作了把無腦迴圈那邊也丟另一個 thread同樣可以解掉更新問提
作者: disabledman (m.m.)   2015-07-17 17:53:00
keyword: invoke doevent

Links booklink

Contact Us: admin [ a t ] ucptt.com