[问题] 执行绪与进度条更新

楼主: 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