C#同步执行委托
namespace SyncDelegate
{
delegate int BinaryOp(int a, int b);
class Program
{
static void Main(string[] args)
{
//打印出正在执行的线程ID。
Console.WriteLine("Main() Invoke:" + Thread.CurrentThread.ManagedThreadId);
Console.Write("请输入i值:");
int i = int.Parse(Console.ReadLine());
Console.Write("请输入j值:");
int j = int.Parse(Console.ReadLine());
//调用地址()以同步的方式。
BinaryOp b = new BinaryOp(Add);
//也可以写b.Invoke(10, 10);
int num= b(i,j);
Console.WriteLine(i + "+" + j + "=" +num);
Console.ReadKey();
}
static int Add(int a, int b)
{
Console.WriteLine("Add() Invoke:" + Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(500);
return a + b;
}
}
}
C#异步执行委托
namespace AsyncDelegate
{
public delegate int BinaryOp(int a ,int b);
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Main()Invoke:"+Thread.CurrentThread.ManagedThreadId);
BinaryOp bin = new BinaryOp(Add);
//BeginInvoke 异步调用委托
IAsyncResult Iasync = bin.BeginInvoke(4,5,new AsyncCallback(AddComplete),"Main()感谢你提供这些参数!");
//担任其他工作是在这里
Console.ReadLine();
}
//异步调用委托之后会执行下面过程,可以取出异步调用委托返回值
public static void AddComplete(IAsyncResult result)
{
Console.WriteLine("AddComplete()Invoke:"+Thread.CurrentThread.ManagedThreadId);
//现在得到的结果。
AsyncResult ar = (AsyncResult)result;
BinaryOp b = (BinaryOp)ar.AsyncDelegate;
//用BeginInvoke 取得返回值
int num = b.EndInvoke(result);
Console.WriteLine("x+y="+ num);
//信息检索的对象,它转换为字符串
string msg = result.AsyncState.ToString();
Console.WriteLine(msg);
}
//地区代表的BinaryOp目标
public static int Add(int x,int y)
{
Console.WriteLine("Add() invoke:"+Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(500);
return x + y;
}
}
}
本文通过示例介绍了C#中委托的同步与异步执行方式。首先展示了一个同步执行委托的例子,并打印出执行线程的ID。随后演示了如何使用BeginInvoke进行异步调用,并通过AddComplete回调获取异步调用的结果。
2192

被折叠的 条评论
为什么被折叠?



