How to use Visual Studio - generated async WCF calls?

前端 未结 4 1161
陌清茗
陌清茗 2020-12-05 20:21

My OperationContract:

public List GetMessages()
        {
            List messages = new List

        
4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-05 20:42

    Your Service Reference can (if you are using .Net 4.5) be set to generate task-based async calls. (Configure Service Reference > check Allow generation of asynchronous operations > select Generate task-based operations) These can be used like any async method. Here's an example of how to use it:

    using (var proxy = new YourServiceClient())
    {
        var t1 = proxy.GetMessagesAsync();
        var t2 = proxy.GetMessagesAsync();
        //they're runnning asynchronously now!
    
        //let's wait for the results:
        Task.WaitAll(t1, t2);
        var result1 = t1.Result;
        var result2 = t2.Result;
        Console.WriteLine(result1);
        Console.WriteLine(result2);
    }
    

    If your client is not using .Net 4.5, you cannot generate service references that use async. You'll have to do it the old fashioned way, using callbacks. Here's an example:

    static void m()
    {
        var proxy = new YourServiceClient();
        proxy.GetMessagesCompleted += proxy_GetMessagesCompleted;
        proxy.GetMessagesAsync();
    }
    
    static void proxy_GetMessagesCompleted(object sender, GetMessagesCompletedEventArgs e)
    {
        var proxy = (IDisposable)sender;
        proxy.Dispose(); //actual code to close properly is more complex
    
        if (e.Error != null)
        {
            // do something about this
        }
    
        var result = e.Result;
        Console.WriteLine(result);
    }
    

    Note that in actual code for either of these scenarios, you shouldn't use using or IDisposable.Dispose() to clean up the client, see Avoiding Problems with the Using Statement and this code to get you started into the confusing world of closing these things.

提交回复
热议问题