必备类库
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>的最后一个参数对应。