您的位置:首页 > 大数据

C# 多线程,解决处理大数据时窗体(不能拖动等)假死现象

2012-07-20 15:12 916 查看
using System.Threading;//引入命名空间

public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}
// 第一种方法:
delegate void MyDel(int i);//此处定义委托应与方法HH的原型一致
MyDel mydel = null;
private void button1_Click(object sender, EventArgs e)
{
mydel = new MyDel(HH);
Thread h = new Thread(new ThreadStart(World));
h.IsBackground = true;
h.Start();

}
void HH(int j)
{
#region 错误方法
//for (int i = 0; i <= j; i++)
//{
// Thread.Sleep(100);
// this.progressBar1.Value = i;
// if (i == 100)
// {
// if(DialogResult.OK== MessageBox.Show("成功","测试",MessageBoxButtons.OKCancel,MessageBoxIcon.Question))
// {
// this.Close();
// }
// }
//}
#endregion
this.progressBar1.Value = j;
this.label1.Text = "当前已完成" + j.ToString() + "%,请稍等……";
if (j == 100)
{
this.Invoke(new MethodInvoker(delegate() { this.label1.Text = "完成"; }));
if (DialogResult.OK == MessageBox.Show("成功2", "测试2", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
{
this.Close();
}
}

}
void World()
{
mydel = new MyDel(HH);
for (int i = 0; i <= 100; i++)
{
Thread.Sleep(100);
BeginInvoke(mydel, new object[] { i });
}

}

//第二种方法
private void button2_Click(object sender, EventArgs e)
{
Thread t = new Thread(new ThreadStart(MessageShow));
t.IsBackground = true;
t.Start();
}
void MessageShow()
{
for (int i = 0; i <= 100; i++)
{
Thread.Sleep(100);
this.Invoke(new MethodInvoker(delegate() { this.label3.Text = "当前已完成" + i + "%,请稍等……"; }));

if (i == 100)
{
this.Invoke(new MethodInvoker(delegate()
{
this.label3.Text = "完成";
if (DialogResult.OK == MessageBox.Show("完成1", "完成1", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
{
this.Close();
}
else
{
}
}));
}
this.Invoke(new MethodInvoker(delegate() { this.progressBar2.Value = i; }));
}
}

//第三种方法
private void button3_Click(object sender, EventArgs e)
{
Thread th = new Thread(new ParameterizedThreadStart(GetPath));
th.IsBackground = true;
th.Start("100");
}
void GetPath(object str)
{
int j = int.Parse(str.ToString());
for (int i = 0; i <= j; i++)
{
Thread.Sleep(100);
this.Invoke(new MethodInvoker(delegate() { this.progressBar3.Value = i; }));
this.Invoke(new MethodInvoker(delegate() { this.label2.Text = "当前已完成" + i.ToString() + "%,请稍等……"; }));
if (i == 100)
{
this.Invoke(new MethodInvoker(delegate() { this.label2.Text = "完成" ; }));
if (DialogResult.OK == MessageBox.Show("成功3", "测试3", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
{
this.Close();
}
}
}
}//此方法必须是Object类型的参数

}
}

另外说明:

在多线程程序中,新创建的线程不能访问UI线程创建的窗口控件,如果需要访问窗口中的控件,可以在窗口构造函数中将CheckForIllegalCrossThreadCalls设置为 false

public Form1() {

InitializeComponent();

CheckForIllegalCrossThreadCalls = false;

}

也可以针对某一控件进行设置,例如:

TextBox.CheckForIllegalCrossThreadCalls = false;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐