【问题标题】:How to convert sync calls to Async call of WCF?如何将同步调用转换为 WCF 的异步调用?
【发布时间】:2015-02-03 11:43:46
【问题描述】:

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

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

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

【问题讨论】:

标签: c# wcf asynchronous


【解决方案1】:

如果你关注这个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;

【讨论】:

  • 这里的AddCompletedEventArgsAddCallback 是什么?
  • AddCompletedEventArgs 是事件处理程序,AddCallback1 是完成时处理的回调方法。我会将其添加到答案中。
  • AddCompleted是一种方法?
  • @user2729272 它是一个代表,即public event System.EventHandler&lt;AddCompletedEventArgs&gt; AddCompleted;
  • 我了解客户服务调用部分。现在我想知道delegate、完成后的代码和Event args操作块要写在哪里?
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多