博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Silverlight_Rest_WCF系列之六:跨线程
阅读量:7103 次
发布时间:2019-06-28

本文共 1727 字,大约阅读时间需要 5 分钟。

跨线程有两种方法。

 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,如需转载请自行联系原作者
你可能感兴趣的文章
我的友情链接
查看>>
Windows 10:现代化世界中安全与身份的守卫者
查看>>
查找相关数据结构和算法
查看>>
Android系统匿名共享内存Ashmem(Anonymous Shared Memory)驱动程序源代码分析(下)
查看>>
我的友情链接
查看>>
将命名规范的一些列文件合并成一个完整的文件
查看>>
数据恢复过程之:服务器raid5两块硬盘离线数据恢复
查看>>
戴尔Dell Latitude E6410/E6510官方拆机图解维修手册
查看>>
SAS硬盘与SATA硬盘的区别
查看>>
html语义化
查看>>
mysql+mha高可用搭建
查看>>
思绪,飘在青山绿水间
查看>>
不同云服务模式下的安全策略解析
查看>>
mysql删除重复数据只保留一条
查看>>
Cubieboard开发环境与Uboot的SD启动卡制作
查看>>
linux中强大且常用命令:find、grep
查看>>
【Objective-C】OC中的数值的概念和常用方法(NSArray和NSMutableArray)
查看>>
linux 系统ubuntu minicom 和cutecom下串口 设置和常见问题。
查看>>
岗位角色管理,打造杰出员工
查看>>
TCP 三次握手 -转载
查看>>