读书人

小弟施用多线程及异步回调碰到了困难

发布时间: 2013-02-24 17:58:56 作者: rapoo

小弟使用多线程及异步回调碰到了困难
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;
using System.Threading.Tasks;
using System.Threading;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

//演示了如何在线程里面取回主界面的窗体text文字,并通过异步重新写到主界面的textbox的text属性上
private void Form1_Load(object sender, EventArgs e)
{
//启动线程
Task t = Task.Factory.StartNew((Action)(() =>
{
//以下内容在线程中操作

//设定异步方法反悔值结果为iasyncresult
//这里跳转到主线程执行(由于主线程挂起,此处死锁)
IAsyncResult result = this.BeginInvoke(new Func<string>
(() =>
{
return this.Text;//必须通过return返回结果
}));



//通过endinvoke方法等待上面的异步执行完毕,并取得结果
string returnValue = this.EndInvoke(result).ToString();

//通过延时启动endinvoke
Thread.Sleep(10);

//通过异步方法,让主线程把返回的结果赋值到textbox控件上
this.BeginInvoke(new Action<string>((vs) =>{
this.textBox1.Text =vs;


} ),returnValue);

}));


t.Wait();//此处如果添加这行代码,结果将使程序挂起,使得begininvoke异步执行无法执行完,结果造成线程中的endinvoke无限的等待下去,造成程序死锁

}
}
}



小弟的问题是,这里如何写等待线程t执行完毕,而不造成死锁?
[解决办法]
着要看你的同步的目的是什么,建议你还是先看看,如何对线程同步,先把那几个方式了解一下,在回头去看你的问题,你这么问,没什么意义

读书人网 >C#

热点推荐