日期:2014-05-17  浏览次数:20895 次

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