Oma*_*Mir 1 c# asynchronous async-await windows-phone-8
我正在尝试为Windows Phone 8编写一个库,并想知道是否可以使用await关键字而不使用回调来使用JSON?或者我误解了它是如何工作的?
基本上我希望应用程序能够说:
string result = Library.Ping(var1, var2);
Run Code Online (Sandbox Code Playgroud)
该库连接到Web服务,并将内容从JSON反序列化为动态对象.然后它将它返回到已将请求发送到库的主应用程序.
如果网站出现故障,请参阅链接答案:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
namespace Win8WinPhone.CodeShare.Extensions
{
public static class HttpExtensions
{
public static Task<Stream> GetRequestStreamAsync(this HttpWebRequest request)
{
var taskComplete = new TaskCompletionSource<Stream>();
request.BeginGetRequestStream(ar =>
{
Stream requestStream = request.EndGetRequestStream(ar);
taskComplete.TrySetResult(requestStream);
}, request);
return taskComplete.Task;
}
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;
}
}
public static class HttpMethod
{
public static string Head { get{return "HEAD";} }
public static string Post { get{return "POST";} }
public static string Put { get{return "PUT";} }
public static string Get { get{return "GET";} }
public static string Delete { get{return "DELETE";} }
public static string Trace { get{return "TRACE";} }
public static string Options { get{return "OPTIONS";} }
public static string Connect { get{return "CONNECT";} }
public static string Patch { get{return "PATCH";} }
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以编写你的函数:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
然后将其称为:
Tweet myTweet = await GetTweet(tweetID);
Run Code Online (Sandbox Code Playgroud)
所有信用都归于:@robertftw链接到:http://www.windowsphonegeek.com/news/windows-8---windows-phone-code-sharing-httpwebrequest-getresponseasync