菜鸟遇到窗体假死,请大侠给帮帮忙
初学者遇到窗体假死,请大侠给帮帮忙。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace FormWhile
{
public partial class Form1 : Form
{
bool boolPause;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
boolPause = false;
if (button1.Text.ToString().Equals("暂停"))
{
button1.Text = "继续";
boolPause = true;
}
button1.Text = "暂停";
for(int i=0; i<100; i++)
{
Application.DoEvents();
if (boolPause)
{
button1.Text = "继续";
return;
}
listBox1.Items.Add("现在是第" + i.ToString() + "次");
for (int j = 0; j <10000; j++)
{
listBox2.Items.Add("现在是第" + j.ToString() + "次");
}
}
button1.Text="执行";
}
}
}
窗体有三个控件:button1、listBox1、listBox2。
点击button1后,拖动窗体、再次点击button1,在内层循环结束前都没有反应,listBox2也没有显示。
初次遇到这个问题,不知道怎么弄,请高人帮忙。
------解决思路----------------------
耗时的操作放在主线程中,发生"假死"是正常的
解决方案是:
把相关操作放入线程,
然后使用委托方式,将数据处理结果与UI进行交互
------解决思路----------------------
用线程就可以了!
------解决思路----------------------
使用线程解决
------解决思路----------------------
主线程阻塞,多线程解决。
------解决思路----------------------
用委托。 请查看 http://dotnet.9sssd.com/winform/art/850
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace FormWhile
{
public partial class Form1 : Form
{
bool boolPause;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
boolPause = false;
if (button1.Text.ToString().Equals("暂停"))
{
button1.Text = "继续";
boolPause = true;
}
button1.Text = "暂停";
for(int i=0; i<100; i++)
{
Application.DoEvents();
if (boolPause)
{
button1.Text = "继续";
return;
}
listBox1.Items.Add("现在是第" + i.ToString() + "次");
for (int j = 0; j <10000; j++)
{
listBox2.Items.Add("现在是第" + j.ToString() + "次");
}
}
button1.Text="执行";
}
}
}
窗体有三个控件:button1、listBox1、listBox2。
点击button1后,拖动窗体、再次点击button1,在内层循环结束前都没有反应,listBox2也没有显示。
初次遇到这个问题,不知道怎么弄,请高人帮忙。
------解决思路----------------------
耗时的操作放在主线程中,发生"假死"是正常的
解决方案是:
把相关操作放入线程,
然后使用委托方式,将数据处理结果与UI进行交互
------解决思路----------------------
用线程就可以了!
------解决思路----------------------
使用线程解决
------解决思路----------------------
主线程阻塞,多线程解决。
------解决思路----------------------
用委托。 请查看 http://dotnet.9sssd.com/winform/art/850