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