简体   繁体   English

异步调用WCF方法

[英]calling WCF method asynchronously

I'm looking for feedback on the following code. 我正在寻找有关以下代码的反馈。 I've read here that I should avoid use of async void. 我在这里读到我应该避免使用异步void。

So as a result I've implemented the following in a method.. 因此,我在方法中实现了以下内容。

foreach (var sample in returns)
{
    _logger.Debug("Calling async method");
    var resultFromMethodCall = CallMethodAsync(uploadReturn);
    _logger.Debug("Continuing....");

}




async Task<Tuple<bool,long>> CallMethodAsync(Sample sampleReturn)
{
    try
    {
        Service1Client client = new Service1Client();
        Tuple<bool, long> results = await client.ValidateSampleReturnAsync(sampleReturn);
        _logger.Debug("call to Sample Return validator completed for sample: {0}", results.Item2);
        return results;
    }
    catch (Exception ex)
    {
        _logger.Error(ex, "Error occured while calling WCF service");
        return new Tuple<bool, long>(false, sampleReturn.Id);
    }
}

When I do nothing with the returned variable resultFromMethodCall, the logging indicates the all is working as I expect. 当我对返回的变量resultFromMethodCall不执行任何操作时,日志记录表明一切都按我的预期进行。 However when I log out items from the variable resultFromMethodCall, it appears that its now running synchronously as it waits for the object to be returned from the call. 但是,当我从变量resultFromMethodCall中注销项目时,它现在正在同步运行,因为它等待从调用返回对象。

Am I missing something obvious here? 我在这里错过明显的东西吗? Or am I completely misunderstanding how this works. 还是我完全误解了它是如何工作的。

CallMethodAsync is correct. CallMethodAsync是正确的。

If you don't await (or Wait) resultFromMethodCall execution will continue while that task is still running. 如果您不等待(或等待),则resultFromMethodCall执行将在该任务仍在运行时继续进行。 Whether you should allow that depends on what you want to happen. 是否允许这样做取决于您要发生的事情。

However when I log out items from the variable resultFromMethodCall it appears that its now running synchronously as it waits for the object to be returned from the call. 但是,当我从变量resultFromMethodCall中注销项目时,它现在正在同步运行,因为它等待从调用返回对象。

If you're using resultFromMethodCall.Result to get the items, then yes, it's blocking and running synchronously. 如果您使用resultFromMethodCall.Result来获取项目,那么可以,它正在阻塞并同步运行。

If you're using await resultFromMethodCall to get the items, then no, it's not running synchronously. 如果您正在使用await resultFromMethodCall来获取项目,则不会,它不会同步运行。 However, it is running sequentially - meaning that the method will "pause" at the await and only continue when the resultFromMethodCall task completes. 但是,它按顺序运行-这意味着该方法将在await时“暂停”,并且仅在resultFromMethodCall任务完成时才继续。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM