我的一些电话在Windows Phone 8上花费的时间较长。称其为异步会给我带来麻烦。
我有时可以同步调用WCF服务方法吗? 这样的任何方式? 需要紧急回应 感谢
答案 0 :(得分:1)
所有对网络的调用都必须异步完成。这些方法的同步版本甚至不存在于SDK中。
你看到了什么样的麻烦?即使您的呼叫是同步的,也不会让它们更快地返回。
答案 1 :(得分:0)
使用扩展方法和TPL异步。
来自here。
示例:
public async Task<string> GetMyData(string urlToCall)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlToCall);
request.Method = HttpMethod.Get;
HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync();
using (var sr = new StreamReader(response.GetResponseStream()))
{
return sr.ReadToEnd();
}
}
扩展方法:
public static class HttpExtensions
{
public static Task<HttpWebResponse> GetResponseAsync(this HttpWebRequest request)
{
var taskComplete = new TaskCompletionSource<HttpWebResponse>();
request.BeginGetResponse(asyncResponse =>
{
try
{
HttpWebRequest responseRequest = (HttpWebRequest)asyncResponse.AsyncState;
HttpWebResponse someResponse = (HttpWebResponse)responseRequest.EndGetResponse(asyncResponse);
taskComplete.TrySetResult(someResponse);
}
catch (WebException webExc)
{
HttpWebResponse failedResponse = (HttpWebResponse)webExc.Response;
taskComplete.TrySetResult(failedResponse);
}
}, request);
return taskComplete.Task;
}
}