如何将同步调用转换为 WCF 的异步调用?

How to convert sync calls to Async call of WCF?

目前我们有几个 WCF 服务。它们被同步调用如下,

XYZ.XYZClient test= new XYZ.XYZClient();
bool result = test.Add(1,2);

谁能解释一下我们如何将其转换为异步调用?

如果你关注这个MSDN article

它将变成:

double value1 = 100.00D;
double value2 = 15.99D;
XYZ.XYZClient test= new XYZ.XYZClient();
test.AddCompleted += new EventHandler<AddCompletedEventArgs>(AddCallback);
test.AddAsync(1, 2);
Console.WriteLine("Add({0},{1})", value1, value2);

操作的事件参数

[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
public partial class AddCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs
{
    private object[] results;

    public AddCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : 
            base(exception, cancelled, userState)
    {       this.results = results;         }

    public double Result
    {
        get            {
            base.RaiseExceptionIfNecessary();
            return ((double)(this.results[0]));
        }
    }
}

完成时执行的代码

// Asynchronous callbacks for displaying results.
static void AddCallback(object sender, AddCompletedEventArgs e)
{
    Console.WriteLine("Add Result: {0}", e.Result);
}

代表

public event System.EventHandler<AddCompletedEventArgs> AddCompleted;

更改您的 wcf-proxies 以生成基于任务的操作并使用 async/await。

XYZ.XYZClient test= new XYZ.XYZClient(); 
bool result = await test.AddAsync(1, 2);