0
全部 -異步委託回調格局利用函數功能
我有異步代表其利用回調圖案的樣本代碼。我使用的是標準代表,下面的代碼工作正常。想要將其轉換爲Func委託(因爲它期待和int並返回一個int),但由於某種原因 - 似乎卡住了。有人可以請幫忙嗎?
class Program
{
public delegate int SomeDelegate(int x);
static void Main(string[] args)
{
Console.WriteLine("This is the CallBack Pattern Technique for Asynchronous Delegates in Threading");
Console.WriteLine("");
SomeDelegate sd = SquareNumber;
Console.WriteLine("[{0}] Before SquareNumber Method invoked.", Thread.CurrentThread.ManagedThreadId);
IAsyncResult asyncRes = sd.BeginInvoke(10, new AsyncCallback(CallbackMethod), null);
Console.WriteLine("[{0}] Back in Main after SquareNumber Method invoked. Doing Extra Processing.", Thread.CurrentThread.ManagedThreadId);
Console.WriteLine("[{0}] Main method processing completed.", Thread.CurrentThread.ManagedThreadId);
Console.ReadLine();
}
static int SquareNumber(int a)
{
Console.WriteLine("[{0}] Inside SquareNumber - invoked. Processing......", Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(5000);
return a * a;
}
static void CallbackMethod(IAsyncResult asyncRes)
{
Console.WriteLine("[{0}] Callback Invoked", Thread.CurrentThread.ManagedThreadId);
AsyncResult ares = (AsyncResult)asyncRes;
SomeDelegate delg = (SomeDelegate)ares.AsyncDelegate;
int res = delg.EndInvoke(asyncRes);
Console.WriteLine("[{1}] Result = {0}", res, Thread.CurrentThread.ManagedThreadId);
}
}
感謝
你已經發布了* does *工作的代碼,但沒有*不工作的代碼 - 這使得修復代碼無法工作的難度更大。 – 2013-05-02 14:46:43
Jon - 我正在學習更多關於通用Func和Action代表的知識,並希望在上面的上下文中使用它。似乎不能通過聲明Func代表的第一行 – Patrick 2013-05-02 14:48:01
因此,張貼代碼給你的問題。我們還沒有看到你所嘗試過的,所以我們看不出有什麼問題。 – 2013-05-02 14:49:22