|
发表于 2014-7-29 21:18:41
|
显示全部楼层
标准异步:
using System;
using System.Threading;
namespace 异步
{
delegate void AsyncFoo(int i);
class Program
{
/// ﹤summary﹥
/// 输出当前线程的信息
/// ﹤/summary﹥
/// ﹤param name="name"﹥方法名称﹤/param﹥
static void PrintCurrThreadInfo(string name)
{
Console.WriteLine("Thread Id of " + name + " is: " + Thread.CurrentThread.ManagedThreadId + ", current thread is "
+ (Thread.CurrentThread.IsThreadPoolThread ? "" : "not ") + "thread pool thread.");
}
/// ﹤summary﹥
/// 测试方法,Sleep一定时间
/// ﹤/summary﹥
/// ﹤param name="i"﹥Sleep的时间﹤/param﹥
static void Foo(int i)
{
PrintCurrThreadInfo("Foo()");
Thread.Sleep(i);
}
/// ﹤summary﹥
/// 投递一个异步调用
/// ﹤/summary﹥
static void PostAsync()
{
AsyncFoo caller = new AsyncFoo(Foo);
caller.BeginInvoke(1000, new AsyncCallback(FooCallBack), caller);
}
static void Main(string[] args)
{
PrintCurrThreadInfo("Main()");
for (int i = 0; i < 5; i++)
{
PostAsync();
}
Console.ReadLine();
}
static void FooCallBack(IAsyncResult ar)
{
PrintCurrThreadInfo("FooCallBack()");
AsyncFoo caller = (AsyncFoo)ar.AsyncState;
caller.EndInvoke(ar);
}
}
} |
|