关于线程刷新窗体的问题(Invoke)
做多线程通知窗体进行刷新,发现很麻烦,因为如果需要刷新的控件有很多的话,就需要写很多个委托,所以自己封装了一下,但是没成功,代码如下
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Threading;
namespace WindowsApplication2
{
class CreateFile : System.Windows.Forms.Form
{
private string _FilePath = "";//创建文件目录
public delegate void FileCreate();
public delegate void FileCreateprogress(int sum, int current);
public event FileCreate FileError;//错误事件
public event FileCreate FileDone;//成功事件
public event FileCreateprogress FileProgress;//通知事件
public CreateFile(string FilePath)//构造函数
{
_FilePath = FilePath;
}
public void StartCreate()//开启线程创建文件
{
Thread TempThread = new Thread(new ThreadStart(_StartCreate));
TempThread.IsBackground=true;
TempThread.Start();
}
private void _StartCreate()//创建文件
{
for (int i = 0; i < 1000; i++)
{
try
{
FileStream TempFileStream = new FileStream(_FilePath + i + ".txt", FileMode.Create);
TempFileStream.Close();
if (FileProgress != null)//通知事件
{
FileCreateprogress filecreate_progress = new FileCreateprogress(FileProgress);
this.Invoke(filecreate_progress, new object[] { 100, i });
}
}
catch
{
if (FileError != null)//错误事件
{
FileCreate filecreate_error = new FileCreate(FileError);
this.Invoke(filecreate_error);
}
}
if (FileDone != null)//完成事件
{
FileCreate filecreate_done = new FileCreate(FileDone);
this.Invoke(filecreate_done);
}
}
}
}
}
调用方法如下
private void button1_Click(object sender, EventArgs e)
{
CreateFile createfile = new CreateFile(@"C:\temp\");
createfile.FileDone += new CreateFile.FileCreate(createfile_FileDone);
createfile.FileError += new CreateFile.FileCreate(createfile_FileError);
createfile.FileProgress += new CreateFile.FileCreateprogress(createfile_FileProgress);
createfile.StartCreate();
}
void createfile_FileProgress(int sum, int current)
{
progressBar1.Minimum = 0;
progressBar1.Maximum = sum;
progressBar1.Value = current;
}
void createfile_FileError()
{
MessageBox.Show("生成发生错误");
}
void createfile_FileDone()
{
MessageBox.Show("生成完毕");
}
一执行就报异常 “在创建窗口句柄之前,不能在控件上调用 Invoke 或 BeginInvoke。”,不明白是怎么回事. 对线程不是很了解,在此请教一下,
想要实现的效果就像许多自定义控件一样,里面用多线程执行一些操作,在通知事件里面直接写操作界面控件的代码就可以,不用写委托