标签:sys sync turned read llb return highlight 通过 class
BeginInvoke方法可以使用线程异步地执行委托所指向的方法。然后通过EndInvoke方法获得方法的返回值(EndInvoke方法的返回值就是被调用方法的返回值),或是确定方法已经被成功调用。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
private delegate int NewTaskDelegate(int ms,string msg);
private static int newTask(int ms, string msg)
{
Console.WriteLine("任务开始");
Thread.Sleep(ms);
Random random = new Random();
int n = random.Next(10000);
Console.WriteLine("任务完成" + msg);
return n;
}
static void Main(string[] args)
{
AsyncCallback asyncCallback = new AsyncCallback(MyAsyncCallback);
NewTaskDelegate task = new NewTaskDelegate(newTask);
IAsyncResult asyncResult = task.BeginInvoke(2000,"fk", asyncCallback, task);
// EndInvoke方法将被阻塞2秒
//int result = task.EndInvoke(asyncResult);
//Console.WriteLine(result);
Console.ReadLine();
}
public static void MyAsyncCallback(IAsyncResult iar)
{
int str;
NewTaskDelegate dlgt = (NewTaskDelegate)iar.AsyncState;
str = dlgt.EndInvoke(iar);
Console.WriteLine("the Delegate call returned string:{0}", str);
}
}
}
c#的BeginInvoke和EndInvoke使用demo
标签:sys sync turned read llb return highlight 通过 class
原文地址:http://www.cnblogs.com/wolfocme110/p/6869032.html