跨线程有两种方法。
1:this.Dispatcher.BeginInvoke
2:SynchronizationContext
在上篇文章中我使用了第一种方法。显然每次都要调用this.Dispatcher.BeginInvoke是一件很“环照”的事情。
为了完善RestInvoke,我打算使用SynchronizationContext类,而SynchronizationContext类要和WebRequest关联。
为什么要和WebRequest关联呢?
因为一个Request对应了一个线程上下文,所以要保存请求时候的线程上下文,然后在成功获取数据后再调用保存的线程上下文来跨线程操作。
首先想到的是装饰模式,当然了,在这里可以用,但是从简单性角度考虑,就把Request和SynchronizationContext一起保存在HttpSyncWebRequest类中了。
/// <summary> /// 同步HttpWebRequest /// </summary> public class HttpSyncWebRequest { public HttpWebRequest HttpWebRequest { get ; set ; } public SynchronizationContext SyncContext { get ; set ; } } 代码很简单就是保存一个HttpWebRequest 和SyncContext对象。
在RestInvoke中,我们要修改GetWebRequest方法。代码如下:
/// <summary> /// 获取WebRequest对象 /// </summary> /// <param name="requestUriString"> 请求的地址 </param> /// <param name="httpMethod"> 请求的方法:GET,PUT,POST,DELETE </param> /// <param name="contentType"> 请求的类型,json:"application/json" </param> /// <returns></returns> public static HttpSyncWebRequest GetWebRequest( string requestUriString, string httpMethod, string contentType) { HttpWebRequest request = (HttpWebRequest)WebRequestCreator.ClientHttp.Create( new Uri(requestUriString)); request.Method = httpMethod; if ( ! string .IsNullOrWhiteSpace(contentType)) { request.ContentType = contentType; } return new HttpSyncWebRequest() { HttpWebRequest = request, SyncContext = SynchronizationContext.Current }; } 不是简单的返回HttpWebRequest对象,返回我们自定义的对象。
接着在每一个需要HttpWebRequest对象的地方使用
HttpSyncWebRequest syncWebRequest = GetWebRequest(requestUriString, httpMethod, "application/json;");
HttpWebRequest webRequest = syncWebRequest.HttpWebRequest;
例如
View Code
View Code
本文转自LoveJenny博客园博客,原文链接:http://www.cnblogs.com/LoveJenny/archive/2011/05/16/2047116.html,如需转载请自行联系原作者