0

I've been writing Windows Phone 8 code that calls a SOAP web service backend. From what I've read, the typical pattern is this:

var client = new KitchenPCSoapClient();

client.LogonCompleted += client_LogonCompleted;
client.LogonAsync(username, password);

To me, this just seems counter intuitive. If I call LogonAsync multiple times with the same client, I don't necessarily want it to use the same LogonCompleted callback every time.

What I'd like is a pattern more like JavaScript, where you pass in a reference to the callback function. More like:

var client = new KitchenPCSoapClient();
client.LogonAsync(username, password, client_LogonCompleted);

Is there a way to implement such a pattern, or should I just force myself to get used to setting the LogonCompleted property before I call LogonAsync, or set the userState property if I want to differentiate between different contexts?

4

2 回答 2

0

您可以使用 Dispatcher 并为此调用 UI 端的函数...

我正在这样做

回调函数

private void AddPricesHandler(CompletedEventArgs response, Exception e)
{
  //your code gose here
}

调用代理调用函数

Proxy.AddData(AddPricesHandler, request);

代理类调用webservice

public void AddData(Action<CompletedEventArgs, Exception> callback, IPVWorkflowService.CreateEditDeletePriceSourceRequest request)
        {
            _workflowProxy.CreateEditDeletePriceSourceAsync(request, callback);
            _workflowProxy.CreateEditDeletePriceSourceCompleted+=new EventHandler<CreateEditDeletePriceSourceCompletedEventArgs>(_workflowProxy_CreateEditDeletePriceSourceCompleted); 
        }

完成函数使用调度程序调用回调函数

    void _workflowProxy_CreateEditDeletePriceSourceCompleted(object sender, CreateEditDeletePriceSourceCompletedEventArgs e)
    {
        try
        {
            this.dispatcher.BeginInvoke((Action)(() =>
            {
                (e.UserState as Action<CompletedEventArgs, Exception>)(e, null);
            }));
        }
        catch (Exception ex)
        {
            this.dispatcher.BeginInvoke((Action)(() =>
            {
                (e.UserState as Action<CompletedEventArgs, Exception>)(e, ex);
            }));
        }
        finally
        {
            _workflowProxy.CreateEditDeletePriceSourceCompleted -= _workflowProxy_CreateEditDeletePriceSourceCompleted;
            _workflowProxy = null;
        }
    }
于 2012-11-22T08:11:16.817 回答
0

Async/Await 的美妙之处在于您不必编写回调,您只需编写看起来像同步的代码,但在后台它是异步执行的:

var client = new KitchenPCSoapClient();
await client.LogonAsync(username, password);

// you get here after the async logon is completed
// do stuff after logon

但是如果你真的想使用回调,你可以在 Task 对象上使用 ContinueWith 方法,它是从异步方法返回的:

var client = new KitchenPCSoapClient();
Task task = client.LogonAsync(username, password);

// this method is called when async execution of task is finished
task.ContinueWith(client_LogonCompleted);
于 2012-11-22T08:26:40.657 回答