关于 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);
}
开始编辑
我开始看到发生了什么。我混合了 WCF 异步模式和普通异步模式。在 WCF 中,使用代理并且 Begin- 和 EndMethod 必须通过代理而不是函数委托。在 WCF 的情况下,铸造工作,在正常情况下不是。WCF 使用 [OperationContract(AsyncPattern = true)] 属性可能是为了强制执行一些不同的模式。结束编辑
为什么出错就行了return (string)(result.AsyncState);
?
生产代码中完全相同的模式是可以的。
其次,为什么不能在Test类的BeginMethod中调试代码?
我只能打破 WorkerFunction。