Search code examples
c#silverlightasynchronousdevforce

Need to wrap my head around Async operations


I have custom control and I have interface this control exposes to it's users.

public interface ILookupDataProvider
{
    string IdColumnName { get; }

    IEnumerable<IDataColumn> Metadata { get; set; }

    void GetDataAsync(string parameters, 
        Action<IEnumerable<object>> onSuccess, Action<Exception> onError);
}

So, it's my attempt to expose async operation in GetDataAsync

But I don't know how to implement this method in my class that implements interface. I understand this portion as I have method which will execute and then onCompletion, onSucess or onError delegate will be called.

Can somebody help with syntax on how to write those?

EDIT:

It's 4.0 and I can't use await commands

EDIT 2:

I use DevForce framework to load data, but for the sake of this sample - let's do WCF service for example. How would I wrap WCF service call in my interface implementation?

Also, do you think it's OK to create interface like this to present async operation? Would you do it differently with event for example?


Solution

  • The basic idea here is that the query will occur an a background thread. Once your operation is complete you would use the onSuccess and onError callbacks in order to report the new values. For example

    void GetDataAsync(
      string parameters, 
      Action<IEnumerable<object>> onSuccess, 
      Action<Exception> onError) {
    
      WaitCallback doWork = delegate { 
        try { 
          IEnumerable<object> enumerable = GetTheData(parameters);
          onSuccess(enumerable);
        } catch (Exception ex) {
          onError(ex);
        }
      };
    
      ThreadPool.QueueUserWorkItem(doWork, null);
    }