使用Invoke调用WCF RIA服务方法时,返回类型是否会影响执行完成的回调?

时间:2013-11-22 17:29:28

标签: wcf silverlight asynchronous wcf-ria-services ria

我继承了Silverlight 5应用程序。在服务器端,它有一个DomainContext(服务),其方法标记为

[Invoke]
public void DoIt
{
 do stuff for 10 seconds here
}

在客户端,它有一个包含以下内容的ViewModel方法:

var q = Context.DoIt(0);
var x=1; var y=2;
q.Completed += (a,b) => DoMore(x,y);

我的2个问题是

1)我附加DoIt时已激活q.Completed

2)返回类型(void)是否完全进入时间?

现在,我知道还有另一种方式来呼叫DoIt,即:

var q = Context.DoIt(0,myCallback);

这让我认为拨打电话的两种方式是相互排斥的。

1 个答案:

答案 0 :(得分:1)

虽然DoIt()是在远程计算机上执行的,但最好立即附加Completed事件处理程序。否则,当该过程完成时,您可能会错过回调。

你是对的。调用DoIt的两种方式是互斥的。

如果您有复杂的逻辑,您可能需要考虑使用Bcl异步库。请参阅此blog post

使用async,您的代码将如下所示:

// Note: you will need the OperationExtensions helper
public async void CallDoItAndDosomething()
{
   this.BusyIndicator.IsBusy = true;
   await context.DoIt(0).AsTask();
   this.BusyIndicator.IsBusy = false;
}

public static class OperationExtensions
{
  public static Task<T> AsTask<T>(this T operation)
    where T : OperationBase
  {
    TaskCompletionSource<T> tcs =
      new TaskCompletionSource<T>(operation.UserState);

    operation.Completed += (sender, e) =>
    {
      if (operation.HasError && !operation.IsErrorHandled)
      {
        tcs.TrySetException(operation.Error);
        operation.MarkErrorAsHandled();
      }
      else if (operation.IsCanceled)
      {
        tcs.TrySetCanceled();
      }
      else
      {
        tcs.TrySetResult(operation);
      }
    };

    return tcs.Task;
  }
}