【编程随笔】C# BeginInvoke+EndInvoke实现异步操作


必备类库

using System;
using System.Runtime.Remoting.Messaging

代码示例

//自定义函数
public string Func(string input)
{
    Console.WriteLine("输入参数:" + input);
    Console.WriteLine("这是执行语句 in 线程:" + System.Diagnostics.Process.GetCurrentProcess().Id.ToString());
    System.Threading.Thread.Sleep(1000);
    return "这是输出";
}

//创建并调用线程
private void Begin()
{
    //声明委托函数
    Func<string, string> func = Func;

    Console.WriteLine("这是调用语句 in 线程:" + System.Diagnostics.Process.GetCurrentProcess().Id.ToString());
    //开始线程
    IAsyncResult iar = func.BeginInvoke("这是输入", CallbackWhenDone, this);
}

//返回值处理函数
private void CallbackWhenDone(IAsyncResult iar)
{
    Func<string, string> func = Func;

    Console.WriteLine("输出:" + func.EndInvoke(iar));
    Console.WriteLine("这是回调语句 in 线程:" + System.Diagnostics.Process.GetCurrentProcess().Id.ToString());
}

注:代码并不能在命令行下执行,所有的 Console.WriteLine()均为自定义语句

注意事项

BeginInvoke(T input, AsyncCallBack callback, object @object);

//需在WinForm下运行代码
//对@object有要求。
//我在命令行下测试会报错 System.PlatformNotSupportedException: Operation is not supported on this platform.
//在WinForm界面编程下就没有问题

public string Func(string input);
Func<string, string> func = Func;
//此处Func的参数列表可以任意指定(数量、类型),返回值则会与Func<T1,T2,(out)T>的最后一个参数对应。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值