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

时间:2015-02-03 11:43:46

标签: c# wcf asynchronous

目前我们有几个WCF服务。它们被称为synchronously如下,

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

有人可以解释一下我们如何将其转换为异步调用吗?

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分:0)

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

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

Service Reference Settings