How can I use async/await to call a webservice?

前端 未结 5 729
清酒与你
清酒与你 2020-12-14 07:08

I have a webservice written in Yii (php framework).

I use C# and Visual Studio 2012 to develop a WP8 application. I added a service reference to my project (Add Serv

5条回答
  •  悲&欢浪女
    2020-12-14 07:30

    (Copied from OP, per https://meta.stackexchange.com/a/150228/136378 )

    Answer:

    Following code seems to work.

    internal static class Extension
    {
        private static void TransferCompletion(
            TaskCompletionSource tcs, System.ComponentModel.AsyncCompletedEventArgs e, 
            Func getResult)
        {
            if (e.Error != null)
            {
                tcs.TrySetException(e.Error);
            }
            else if (e.Cancelled)
            {
                tcs.TrySetCanceled();
            }
            else
            {
                tcs.TrySetResult(getResult());
            }
        }
    
        public static Task LoginAsyncTask(
            this YChatWebService.WebServiceControllerPortTypeClient client,
            string userName, string password)
        {
            var tcs = new TaskCompletionSource();
            client.loginCompleted += (s, e) => TransferCompletion(tcs, e, () => e);
            client.loginAsync(userName, password);
            return tcs.Task;
        }
    }
    

    I call it this way

    client = new YChatWebService.WebServiceControllerPortTypeClient();
    var login = await client.LoginAsyncTask(this.username, this.password);
    

提交回复
热议问题