0
我寫的輔助類來檢索Web服務數據在Silverlight中使用:Silverlight:如何在異步HttpWebRequest完成時更新UI?
public static class RequestMethod
{
public static string Get = "GET";
public static string Post = "POST";
}
public static class RequestDataType
{
public static string Xml = "Xml";
public static string Json = "application/json";
}
public class HttpWebRequestHelper<T>
{
private readonly SynchronizationContext _context;
private readonly ObservableCollection<T> _collection =
new ObservableCollection<T>();
public ObservableCollection<T> Collection
{
get { return _collection; }
}
public HttpWebRequestHelper()
{
_context = SynchronizationContext.Current;
}
public ObservableCollection<T> GetCollection()
{
if (HttpWebRequest == null) throw new ArgumentNullException("request");
HttpWebRequest.BeginGetResponse((result) =>
{
var response = HttpWebRequest.EndGetResponse(result);
var stream = response.GetResponseStream();
if (stream == null) return;
var reader = new StreamReader(stream, Encoding.UTF8);
var responseString = reader.ReadToEnd();
var desirilizedObject = JsonConvert.DeserializeObject<IEnumerable<T>>(responseString);
_context.Post((state) =>
{
Collection.Clear();
foreach (var item in desirilizedObject)
{
Collection.Add(item);
}
}, null);
}, null);
return Collection;
}
private HttpWebRequest HttpWebRequest { get; set; }
public void CreateRequest (string url,string requestMethod, string requestDataType)
{
var uri = new Uri(url, UriKind.Absolute);
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = requestMethod;
request.Accept = requestDataType;
HttpWebRequest= request;
}
}
這是我班的樣本用法:
var request = new HttpWebRequestHelper<DriverModel>();
request.CreateRequest("http://localhost:11624/api/Drivers/", RequestMethod.Get, RequestDataType.Json);
request.GetCollection();
this.DataContext = request;
我想更新UI HttpWebRequest的完成時。 我該怎麼做?