When calling a WCF RIA Service method using Invoke, does the return type affect when the Completed callback is executed?

StackOverflow https://stackoverflow.com/questions/20150945

문제

I inherited a Silverlight 5 application. On the server side, it has a DomainContext (service) with a method marked as

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

On the client side, it has a ViewModel method containing this:

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

My 2 questions are

1) has DoIt already been activated by the time I attach q.Completed, and

2) does the return type (void) enter into the timing at all?

Now, I know there's another way to call DoIt, namely:

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

This leads me to think the two ways of making the call are mutually exclusive.

도움이 되었습니까?

해결책

Although DoIt() is executed on a remote computer, it is best to attach Completed event handler immediately. Otherwise, when the process completes, you might miss out on the callback.

You are correct. The two ways of calling DoIt are mutually exclusive.

If you have complicated logic, you may want to consider using the Bcl Async library. See this blog post.

Using async, your code will look like this:

// 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;
  }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top