网上找了相关的例子,尝试不行呀? 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#线程
解决方案 »
- mapobject的用处及下载地址
- c# winddows服务问题
- 疯了!!这么简单几行代码都运行不来!!???菜鸟严重求问!!!
- 请教 程序运行时,如果检测到程序已经有一个实例在运行了,就退出,并激活运行的实例的问题
- textbox AutoCompleteSource怎样与dataset相关联
- 由于目标机器积极拒绝,无法连接的问题
- Socket简单编程
- Active Directory 创建用户出错
- 在哪可以下《C#与.NET技术平台实战演练》的电子书
- 怎么在listView上点击鼠标右键时弹出菜单阿。
- 用C#如何实现搜狗插入表情图功能?
- 一个简单的问题,关于string.format中的换行
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表达式