2012-06-21 103 views
1

我有一个现有的RIA服务,我想在其中包含一个非常简单的调用来查找某个自定义对象允许的最大字段。这个值很少会改变,如果有的话,我想在需要时只调用一次,然后保存在客户端。但是,当我需要知道价值时,我需要以同步的方式了解它,因为我将立即使用它。如何进行同步RIA请求

我试过以下方法,但.Value始终只是0,因为当这段代码运行时服务实际上没有发出请求,而是稍后一段时间。

private static readonly Lazy<int> _fieldCount = 
    new Lazy<int>(() => 
     { 
      const int TotalWaitMilliseconds = 2000; 
      const int PollIntervalMilliseconds = 500; 

      // Create the context for the RIA service and get the field count from the server. 
      var svc = new TemplateContext(); 
      var qry = svc.GetFieldCount(); 

      // Wait for the query to complete. Note: With RIA, it won't. 
      int fieldCount = qry.Value; 
      if (!qry.IsComplete) 
      { 
       for (int i = 0; i < TotalWaitMilliseconds/PollIntervalMilliseconds; i++) 
       { 
        System.Threading.Thread.Sleep(PollIntervalMilliseconds); 
        if (qry.IsComplete) break; 
       } 
      } 

      // Unfortunately this assignment is absolutely worthless as there is no way I've discovered to really invoke the RIA service within this method. 
      // It will only send the service request after the value has been returned, and thus *after* we actually need it. 
      fieldCount = qry.Value; 

      return fieldCount; 
     }); 

任何方式,使使用RIA服务同步,负载点播服务呼叫?或者我必须要么:1)在客户端代码中包含常量,并在/如果它发生更改时推出更新;或2)主持一个完全独立的服务,我可以以同步方式调用?

+0

回调/代表呢? –

回答

3

不幸的是,您无法使WCF RIA同步工作。你可以做的是将<object>标记的InitParams的值放在承载Silverlight的HTML中。阅读更多:http://msdn.microsoft.com/en-us/library/cc189004(v=vs.100).aspx

+0

在我的情况下,RIA服务与Silverlight主机位于同一台服务器上,我的'_fieldCount'的用法非常适合InitParam的形式,所以这对我来说很合适。我仍然对任何其他解决方案感兴趣,以防其他问题出现在会议期间价值可能发生变化的地方。谢谢! –

1

我意识到前面的答案在几年前可能是真实的,但现在并不完全如我刚发现的那样。看看等待运营商http://msdn.microsoft.com/en-us/library/hh156528.aspx

我想这正是你在找什么。你可以在异步方法中调用它(必须在方法的开头使用async修饰符,如:private async void dostuff())。尽管父方法仍然是异步的,它将等待对任务的调用。

假设您是通过域数据服务完成此操作的。以下是一个示例: 注意:您的DDS必须返回一种IEnumerable类型。您从DDS调用数据之前,确定哪些检索有问题的数据是这样的私人任务方法:

private Task<IEnumerable<fieldCounts>> GetCountssAsync() 
    { 
     fieldCountsEnumerable_DS _context = new fieldCountsEnumerable_DS(); 
     return _context.LoadAsync(_context.GetCountsQuery()); 
    } 

然后,您可以调用任务从现有的异步RIA服务方法或真正使用任何客户端方法中的await :

IEnumerable<fieldCounts> fieldcnts = await GetCountssAsync(); 
enter code here 

只要知道无论您调用此方法的哪种方法,该方法必须像文档中所述的那样是异步的。它必须将控制权交还给调用者。