using System;
using System.Threading;
namespace AsyncDelegateDemo
{
delegate void AsyncFoo(int i);
class Program
{
///
/// 输出当前线程的信息
///
/// 方法名称
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.");
}
///
/// 测试方法,Sleep一定时间
///
/// Sleep的时间
static void Foo(int i)
{
PrintCurrThreadInfo("Foo()");
Thread.Sleep(i);
}
///
/// 投递一个异步调用
///
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 < 10 ; i++)
{
PostAsync();
}
Console.ReadLine();
}
static void FooCallBack(IAsyncResult ar)
{
PrintCurrThreadInfo("FooCallBack()");
AsyncFoo caller = (AsyncFoo) ar.AsyncState;
caller.EndInvoke(ar);
}
}
}
Thread Id of Main() is: 1, current thread is not thread pool thread.
Thread Id of Foo() is: 3, current thread is thread pool thread.
Thread Id of FooCallBack() is: 3, current thread is thread pool thread.
Thread Id of Foo() is: 3, current thread is thread pool thread.
Thread Id of Foo() is: 4, current thread is thread pool thread.
Thread Id of Foo() is: 5, current thread is thread pool thread.
Thread Id of FooCallBack() is: 3, current thread is thread pool thread.
Thread Id of Foo() is: 3, current thread is thread pool thread.
Thread Id of FooCallBack() is: 4, current thread is thread pool thread.
Thread Id of Foo() is: 4, current thread is thread pool thread.
Thread Id of Foo() is: 6, current thread is thread pool thread.
Thread Id of FooCallBack() is: 5, current thread is thread pool thread.
Thread Id of Foo() is: 5, current thread is thread pool thread.
Thread Id of Foo() is: 7, current thread is thread pool thread.
Thread Id of FooCallBack() is: 3, current thread is thread pool thread.
Thread Id of Foo() is: 3, current thread is thread pool thread.
Thread Id of FooCallBack() is: 4, current thread is thread pool thread.
Thread Id of FooCallBack() is: 6, current thread is thread pool thread.
Thread Id of FooCallBack() is: 5, current thread is thread pool thread.
Thread Id of FooCallBack() is: 7, current thread is thread pool thread.
Thread Id of FooCallBack() is: 3, current thread is thread pool thread.
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/12639172/viewspace-526512/ ,如需转载,请注明出处,否则将追究法律责任。