C# 的异步调用 线程返回值 AsyncResult

MSDN 介绍 HTTP


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using TestEvent;
using System.Threading;
using System.Runtime.Remoting.Messaging;

namespace WdjCSharp
{
    public delegate bool DelegtaeTestFunc();        // 声明回调函数
    public delegate String TwoReturn(int a);

    public partial class WdjControl : Form
    {
        public event DelegtaeTestFunc TestFunc = null;     // 定义一个回调函数变量 相当于定义一个回调函数的指针。
        private Thread m_ThreadRun1 = null;

        public WdjControl()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //this.TestFunc = Class1.TestFunc;          // 给回调函数指针赋值
            //TestFunc();                               // 调用回调函数
            //m_ThreadRun1 = new Thread( new ThreadStart(TestFunc) ); 
            FuncInvoke();

        }

        public void FuncInvoke()
        {

            TwoReturn handler = new TwoReturn(Class1.Add);

            //用BeginInvoke开始异步操作 这里的 1,"字符串",这两个参数就是对应(int a, string b)
            IAsyncResult result = handler.BeginInvoke(1,  new AsyncCallback(AddComplete), this);

        }

        public static String Add(int a)
        {
            //这里是处理的的函数
            return a.ToString();
        }

        public static void AddComplete(IAsyncResult result)
        {
            TwoReturn handler = (TwoReturn)((AsyncResult)result).AsyncDelegate;

            //调试一下就会明白了
            MessageBox.Show(handler.EndInvoke(result));
            MessageBox.Show(result.AsyncState.ToString());
        }
    }
}


你可能感兴趣的:(C#)