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执行完毕,而不造成死锁?
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执行完毕,而不造成死锁?
解决方案 »
- “System.Data.DataSet”不包含“GetEnumerator”的公共定义,因此 foreach 语句不能作用于“System.Data.Data
- public interface IAccess< in T> 报 type expected 错误?
- .net编写的winform程序,无法启动
- float 强制转换为 int 出错?
- 谁有兴趣做用在PDA上的餐饮点菜程序?
- DataList问题,在线等
- SQL用视图!2个同样的表!这样的结构怎么操作啊!
- 获取嵌套框架中的html源码
- 如何制作计时器
- C# 问大家一个问题,主窗体里面嵌套了一个子窗体,子窗体里的DataGridVIew控件有数据不显示
- xml 反序列化 子节点上移。
- 准备做一个在线考试系统,有几个问题请教各位。
怎么解决呢?
webtestthread = new Task<string>[p.weburlarraylist.Count];
int js = 0;
foreach (var item in weburlarraylist)
{
webtestthread[js] = Task<string>.Factory.StartNew(u => p.dotest((string)u), item);
js = js + 1;
}
js = 0;
Task tast = Task.Factory.StartNew(new Action<object >(obj=> {
Task.WaitAll((Task[])obj);
MessageBox.Show("该线程组执行完毕");
}),webtestthread);
#endregion
哎 一不小心自己把问题解决了。可惜不能自己给自己分。