您的位置:首页 > 其它

Silverlight 中实现Service同步调用

2011-09-26 18:53 507 查看

Silverlight中实现Service同步调用

Silverlight中实现同步调用Service,核心是用到了MS的Interlocked.Increment.

Interlocked.Increment是做什么事情的?
如果有两个Thread,分别记作threadA,threadB。

1:threadA将Value从存储空间取出,为0;

2:threadB将Value从存储空间取出,为0;

3:threadA将取出来的值和1作加法,并且将和放回Value的空间覆盖掉原值。加法结束,Value=1。

4:threadB将取出来的值和1作加法,并且将和放回Value的空间覆盖掉原值。加法结束,Value=1。

最后Value=1,而正确应该是2;这就是问题的所在,InterLockedIncrement能够保证在一个线程访问变量时其它线程不能访问。

不废话了,直接上Demo了。

viewsourceprint?

private
BizModelbizModel=
null
;
public
void
LoadData()
{
int
loadCompletedCount=0;
int
wellLoadedCount=3;
RestService.Query<BizEntity>(
"/Biz1/1000"
,(obj,args)=>
{
Interlocked.Increment(
ref
loadCompletedCount);
    
//businesscode
bizModel=args.Result.ToModel();
   
if
(loadCompletedCount==wellLoadedCount)
{
UpdateUIAfterLoadData();
}
}
RestService.Query<BizEntity>(
"/Biz2/1000"
,(obj,args)=>
{
Interlocked.Increment(
ref
loadCompletedCount);
    
//businesscode
bizModel=args.Result.ToModel();
   
if
(loadCompletedCount==wellLoadedCount)
{
UpdateUIAfterLoadData();
}
}
RestService.Query<BizEntity>(
"/Biz3/1000"
,(obj,args)=>
{
Interlocked.Increment(
ref
loadCompletedCount);
    
//businesscode
bizModel=args.Result.ToModel();
   
if
(loadCompletedCount==wellLoadedCount)
{
UpdateUIAfterLoadData();
}
}
}
private
void
UpdateUIAfterLoadData()
{
//RefreshUIbybizModel;
}
测试例子

public
delegate
void
deleHeadler(
object
x,EventArgse);
02
03
public
class
RestService
04
{
05
public
static
void
Query<T>(
string
s,deleHeadlerdel)
06
{
07
Console.WriteLine(s);
08
for
(
int
i=0;i<70000000;i++)
09
{
10
11
}
12
del(
null
,
null
);
13
}
14
}
15
16
public
class
Program
17
{
18
static
void
Main(
string
[]args)
19
{
20
int
wellLoadedCount=2;
21
int
loadCompletedCount=0;
22
23
RestService.Query<
string
>(
"1"
,
24
(obj,argsOne)=>
25
{
26
Interlocked.Increment(
ref
loadCompletedCount);
27
28
if
(loadCompletedCount==wellLoadedCount)
29
{
30
UpdateUIAfterLoadData();
31
}
32
});
33
34
35
RestService.Query<
string
>(
"2"
,
36
(obj,argsTwo)=>
37
{
38
Interlocked.Increment(
ref
loadCompletedCount);
39
40
if
(loadCompletedCount==wellLoadedCount)
41
{
42
UpdateUIAfterLoadData();
43
}
44
});
45
Console.ReadKey();
46
}
47
48
private
static
void
UpdateUIAfterLoadData()
49
{
50
Console.WriteLine(
"全部加载完毕"
);
51
}
52
}
53
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: