【问题标题】:Does this async method using TaskCompletionSource make any sense?这种使用 TaskCompletionSource 的异步方法是否有意义?
【发布时间】:2017-02-05 20:17:02
【问题描述】:

我正在尝试理解一段不是我自己编写的代码。这是一种用于发送电子邮件的异步方法,最多应尝试 5 次以发送给定的邮件消息。

public Task<bool> SendMail(MailMessage mailMessage)
{
    bool success = false;

    int i = 0;
    int smtpRetryCount = 5;
    SmtpClient smtpClient = new SmtpClient("myprovider.de");
    smtpClient.Port = 123;
    smtpClient.EnableSsl = true;

    int smtpRetryWaitTime = 2000;

    while (i < smtpRetryCount + 1)
    {
        try
        {
            smtpClient.Send(mailMessage);
            success = true;
            Console.WriteLine("SUCCESS");
            break;
        }
        catch (Exception exc)
        {
            Console.WriteLine("Exception");
            Thread.Sleep(smtpRetryWaitTime);
            success = false;
        }

        i++;
    }

    // This is the part that I don't get, does it make any sense?
    TaskCompletionSource<bool> tsc = new TaskCompletionSource<bool>();
    tsc.SetResult(success);
    return tsc.Task;
}

我想知道这是否真的是异步的,如果是,它以何种方式实现异步属性。对我来说这没有多大意义,尤其是最后 4 行。

【问题讨论】:

  • 整个方法没有意义,因为它是同步的。

标签: c# asp.net .net asynchronous async-await


【解决方案1】:

这样做是因为您希望 API 可能是异步的,而实现决定它实际上是异步的还是同步的。

就此而言,您可以使用TaskCompletionSource&lt;TResult&gt;Task.FromResult&lt;TResult&gt;(TResult result)Task.FromCanceledTask.FromException

为什么建议采用这种方法?

通常您遵循这种方法/原则,因为您可以通过交换实现轻松地使相同的 API 以异步方式工作,而将已经同步的 API 变为 异步则需要进行密集且长时间的重构改变成为可能。

归根结底,由于 awaitablesasync-await

的奇迹,您应该不会发现以这种方式实现 API 的巨大差异

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-04
    • 1970-01-01
    • 1970-01-01
    • 2021-02-07
    • 2017-07-10
    相关资源
    最近更新 更多