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执行完毕,而不造成死锁?

解决方案 »

  1.   

    我的问题其实翻译一下就是当主线程启动等待线程完成的命令时候,线程有个begininvoke回回到主线程,此时死锁。
    怎么解决呢?
      

  2.   

        #region 启动线程执行测试
                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
    哎  一不小心自己把问题解决了。可惜不能自己给自己分。