Silverlight 中实现Service同步调用

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了。

private BizModel bizModel = null;
public void LoadData()
{
    int loadCompletedCount = 0;
    int wellLoadedCount = 3;
 
 
    RestService.Query<BizEntity>("/Biz1/1000",(obj,args)=>
    {
        Interlocked.Increment(ref loadCompletedCount);
 
     //business code
        bizModel = args.Result.ToModel();
 
         if (loadCompletedCount == wellLoadedCount)
            {
               UpdateUIAfterLoadData();
            }
 
    }
 
    RestService.Query<BizEntity>("/Biz2/1000",(obj,args)=>
    {
        Interlocked.Increment(ref loadCompletedCount);
 
     //business code
        bizModel = args.Result.ToModel();
 
         if (loadCompletedCount == wellLoadedCount)
            {
               UpdateUIAfterLoadData();
            }
 
    }
    RestService.Query<BizEntity>("/Biz3/1000",(obj,args)=>
    {
        Interlocked.Increment(ref loadCompletedCount);
 
     //business code
        bizModel = args.Result.ToModel();
 
         if (loadCompletedCount == wellLoadedCount)
            {
               UpdateUIAfterLoadData();
            }
 
    }
}
 
private void UpdateUIAfterLoadData()
{
    //Refresh UI by bizModel;
}
测试例子
public delegate void deleHeadler(object x, EventArgs e);
02  
03 public class RestService
04 {
05     public static void Query<T>(string s, deleHeadler del)
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  
posted @ 2011-09-26 18:53  Areas  阅读(155)  评论(0编辑  收藏  举报