在异步调用中不执行回调函数
问题描述:
我正在尝试使用WCF进行简单的异步调用,但从不执行回调函数。任何人都可以告诉我代码有什么问题吗?在异步调用中不执行回调函数
我使用Visual Studio 2008与.net 3.5
服务代码
[ServiceContract]
public interface IService1
{
[OperationContract(AsyncPattern = true) ]
IAsyncResult BeginGetData(string value, AsyncCallback callback, object state);
string EndGetData(IAsyncResult result);
}
public class Service1 : IService1
{
#region IService1 Members
public IAsyncResult BeginGetData(string value, AsyncCallback callback, object state)
{
return new CompletedAsyncResult<string>(value, state);
}
public string EndGetData(IAsyncResult r)
{
CompletedAsyncResult<string> result = r as CompletedAsyncResult<string>;
return result.Data;
}
#endregion
}
客户端代码
class Program
{
static void Main(string[] args)
{
Service1Client client = new Service1Client();
Console.WriteLine("Start async call");
IAsyncResult result = client.BeginGetData("abc", callback, null);
Console.ReadLine();
}
static void callback(IAsyncResult result)
{
string a = "in callback";
Console.WriteLine(a);
}
}
答
你需要显式调用回调函数。
IAsyncResult result = client.BeginGetData("abc", callback, null);
callback(result);
Console.ReadLine();
请参阅此处参考。
+1是的,你错过了最基本的部分。如果你没有在BeginInvoke中指定回调,它将如何被调用? 另一个链接供大家参考http://*.com/questions/1047662/what-is-asynccallback/1047677#1047677 http://msdn.microsoft.com/en-us/library/2e08f6yc.aspx – 2009-11-22 06:11:01