有关AsyncCallback和IAsyncResult的回调模式的两个问题。有关AsyncCallback和IAsyncResult模式的两个问题
我改变的问题与代码示例:
using System;
using System.Collections.Generic;
using System.Text;
namespace TestAsync
{
class Program
{
private static Wrapper test = new Wrapper();
static void Main(string[] args)
{
test.BeginMethod("parameter 1", "parameter 2", Callback);
Console.ReadKey();
}
private static void Callback(IAsyncResult ar)
{
string result = test.EndMethod(ar);
}
}
public interface ITest
{
IAsyncResult BeginMethod(string s1, string s2, AsyncCallback cb, object state);
string EndMethod(IAsyncResult result);
}
public class Wrapper
{
private ITest proxy = new Test();
public void BeginMethod(string s1, string s2, AsyncCallback cb)
{
proxy.BeginMethod(s1, s2, cb, proxy);
}
public string EndMethod(IAsyncResult result)
{
return ((ITest)(result.AsyncState)).EndMethod(result);
}
}
public class Test : ITest
{
private string WorkerFunction(string a, string b)
{
// "long running work"
return a + "|" + b;
}
public IAsyncResult BeginMethod(string s1, string s2, AsyncCallback cb, object state)
{
Func<string, string, string> function = new Func<string, string, string>(WorkerFunction);
IAsyncResult result = function.BeginInvoke(s1, s2, cb, state);
return result;
}
public string EndMethod(IAsyncResult result)
{
return (string)(result.AsyncState);
}
}
public delegate TResult Func<T1, T2, TResult>(T1 t1, T2 t2);
}
BEGIN编辑
我开始看是怎么回事。 我已经混合了一个WCF异步模式和一个正常的异步模式。 在WCF中,一个使用代理,Begin-和EndMethod必须通过代理而不是函数委托。在WCF的情况下,铸件起作用,在正常情况下不起作用。 WCF使用[OperationContract(AsyncPattern = true)]属性可能会强制执行某种不同的模式。 END编辑
为什么错误就行return (string)(result.AsyncState);
?
生产代码中的模式完全相同。
其次,为什么我不能在类Test的BeginMethod中调试代码?
我只能在WorkerFunction中断。
您可以使用'object @ object'状态参数填充委托函数 - 您知道这是否是必需的吗? – Gerard 2011-02-23 13:20:48
而不是'IAsyncResult result = function.BeginInvoke(...'你也可以做'function.BeginInvoke(...'? – Gerard 2011-02-23 13:35:07
对不起,CallBack应该是WorkerFunction,我现在就改变它。用@object状态参数填充委托函数,但是你可以看到这样做可以让你访问回调函数体内的委托,你需要从回调函数中调用委托的EndInvoke,所以你需要委托函数引用那里。是的,你可以简单地做function.BeginInvoke。我保持使用与你使用的语法相同的语法。正如你所看到的,我不会在BeginInvoke – Nikhil 2011-02-23 14:13:15