作者honoYang (......)
看板C_Sharp
标题[问题] 执行绪与进度条更新
时间Wed Jun 24 12:54:34 2015
最近在实作进度条更新
在网上也看了一些范例
但轮到自己实作时却卡住了
环境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://webptt.com/cn.aspx?n=bbs/C_Sharp/M.1435121678.A.892.html
1F:→ honoYang: 自己解答一下 不确定有无错 因为UI不一定会即时更新 06/25 23:55
2F:→ honoYang: 所以要在忙碌的地方(for回圈内)加入application.doevent 06/25 23:56
3F:→ honoYang: 更新UI 06/25 23:56
4F:→ honoYang: google 关键字 C# UI响应 thread 06/25 23:57
5F:→ FancyWing: 应该说,UI thread 被 button1_click 卡住了,因此 06/27 17:03
6F:→ FancyWing: t thread 就算有更新资料,但 btn1_click 没有 release 06/27 17:04
7F:→ FancyWing: UI 会不更新,因此已知问题,加入 app.do~ 可以让 06/27 17:05
8F:→ FancyWing: UI thread 跳出去处理 其他 UI thread 的事件 06/27 17:06
9F:→ FancyWing: 漏说了,如果 processBar1 跟 btn1 不属於同一个thread 06/27 17:07
10F:→ FancyWing: 是不会发生这样事情的,不过 会造成 processBar 没跑完 06/27 17:08
11F:→ FancyWing: 但主UI已经可以被操作了 06/27 17:09
12F:→ FancyWing: 把无脑回圈那边也丢另一个 thread同样可以解掉更新问提 06/27 17:10
13F:→ disabledman: keyword: invoke doevent 07/17 17:53