网上找了相关的例子,尝试不行呀? public partial class Form1 : Form
{
private delegate void DelegateFunction();//代理 public Form1()
{
InitializeComponent();
} private void Form1_Load(object sender, EventArgs e)
{ Thread thread = new Thread(CrossThreadFlush);
thread.IsBackground = true;
thread.Start(); }
//线程2的执行方法
private void CrossThreadFlush()
{
DelegateFunction df = new DelegateFunction(ThreadFunction);
df.BeginInvoke(null, null);
//this.BeginInvoke(df);//这样不报错,但界面会感觉死掉了
} //用代理调用主线程的控件
private void ThreadFunction()
{ try
{
while (true)
{
this.label1.Text = DateTime.Now.ToString();
Thread.Sleep(1000);
} }
catch(System.Exception ex)
{ //这里依然报错
}
} }
C#线程
{
private delegate void DelegateFunction();//代理 public Form1()
{
InitializeComponent();
} private void Form1_Load(object sender, EventArgs e)
{ Thread thread = new Thread(CrossThreadFlush);
thread.IsBackground = true;
thread.Start(); }
//线程2的执行方法
private void CrossThreadFlush()
{
DelegateFunction df = new DelegateFunction(ThreadFunction);
df.BeginInvoke(null, null);
//this.BeginInvoke(df);//这样不报错,但界面会感觉死掉了
} //用代理调用主线程的控件
private void ThreadFunction()
{ try
{
while (true)
{
this.label1.Text = DateTime.Now.ToString();
Thread.Sleep(1000);
} }
catch(System.Exception ex)
{ //这里依然报错
}
} }
C#线程
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent(); System.Threading.Thread th1 = new System.Threading.Thread(Function);
th1.Start();
} void Function()
{
while (true)
{
this.Invoke((Action<string>)delegate(string DateTimeNow)
{
this.Text = DateTimeNow;
}, DateTime.Now.ToString());
System.Threading.Thread.Sleep(1000);
}
}
}
this.Invoke(new MethodInvoker(delegate
{
//访问主界面控件代码
}));
WPF:
this.Dispatcher.Invoke(new Action(delegate(){
//访问主界面控件代码
}));
我是通过委托呀。 private void CrossThreadFlush()
{
DelegateFunction df = new DelegateFunction(ThreadFunction);
df.BeginInvoke(null, null);
//this.BeginInvoke(df);//这样不报错,但界面会感觉死掉了
}
我这里有调用,但是界面死掉了 //线程2的执行方法
private void CrossThreadFlush()
{
DelegateFunction df = new DelegateFunction(ThreadFunction);
//df.BeginInvoke(null, null);
this.BeginInvoke(df); }
但是
while (true) { this.label1.Text = DateTime.Now.ToString(); Thread.Sleep(1000); }
这是一个死循环,要知道这个委托还是在界面线程里执行的,你把界面线程给阻塞了,当然界面就无响应了你不能把那个死循环放在invoke里面,二楼的思路是对的
我这里有调用,但是界面死掉了 //线程2的执行方法
private void CrossThreadFlush()
{
DelegateFunction df = new DelegateFunction(ThreadFunction);
//df.BeginInvoke(null, null);
this.BeginInvoke(df); }
你这感觉死掉了是怎么回事?你看看任务管理器里,你这个程序是无响应的吗?
Control.CheckForIllegalCrossThreadCalls = false;
解决方法2:
使用BackgroundWorker控件
解决方法3:
使用委托
解决方法4:
使用Lambda表达式