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

本文通过一个具体的 C# 代码示例介绍了如何使用委托进行异步操作,包括 BeginInvoke 和 EndInvoke 的使用方法,并展示了如何通过回调函数处理异步任务的结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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());
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

chen249191508

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值