将布尔方法转换为异步方法

时间:2018-09-05 20:08:16

标签: c# asynchronous

我有执行电子邮件发件人的方法,如下所示:

public void SendIt() 
{
    if (_Error && !_Override) return;

    var html = new StringBuilder();
    html.Append(HTMLHeader());
    html.Append(Body);
    html.Append(HTMLClose());

    IsHTML = true;
    SendAsync = true;
    Body = html.ToString();
    Send();
}

我想将此方法更改为异步方法,所以我这样做:

public async void SendIt() 
{
    await Send();
}

但是我明白了

  

'bool'不包含'GetAwaiter'的定义,并且不   扩展方法'GetAwaiter'接受类型的第一个参数   可以找到“布尔”(您是否缺少using指令或   程序集参考?)

发送方法:

public bool Send() 
{
    var MailFrom = new MailAddress(_From, _From);
    _Email.From = MailFrom;

    if (_To.IndexOf(';') > -1) 
    {
        string[] tolist = _To.Split(';');
        foreach (string toAddress in tolist) 
            _Email.To.Add(new MailAddress(toAddress.Trim()));
    }
    else _Email.To.Add(new MailAddress(_To.Trim()));        

    if (_CC != null && _CC.Length > 5) 
    {
        if (_CC.IndexOf(';') > -1) 
        {
            string[] Cclist = _CC.Split(';');
            foreach (string ccAddress in Cclist) 
                _Email.CC.Add(new MailAddress(ccAddress.Trim()));
        }
        else _Email.CC.Add(new MailAddress(_CC.Trim()));
    }

    if (_BCC != null && _BCC.Length > 5) 
    {
        if (_BCC.IndexOf(';') > -1) 
        {
            string[] Bcclist = _BCC.Split(';');
            foreach (string bccAddress in Bcclist) 
               _Email.Bcc.Add(new MailAddress(bccAddress.Trim()));
        }
        else _Email.Bcc.Add(new MailAddress(_BCC.Trim()));
    }

    _Email.Subject      = _Subject;
    _Email.IsBodyHtml   = _isHTML;
    _Email.Body         = _Body;
    _Email.BodyEncoding = Encoding.UTF8;

    // Smtp Client
    var Connection = new SmtpClient(_Server, _Port) 
    {
        DeliveryMethod = SmtpDeliveryMethod.Network,
        Timeout = 60000
    };

    if (_UserName.Length > 1 && _Password.Length > 1 && _Domain.Length > 1) 
        Connection.Credentials = new NetworkCredential(_UserName, _Password, _Domain);
    else if (_UserName.Length > 1 && _Password.Length > 1) 
        Connection.Credentials = new NetworkCredential(_UserName, _Password);

    bool bFlag = true;

    Connection.EnableSsl = _SSL;

    try 
    {
        Connection.Send(_Email);
    } 
    catch (SmtpFailedRecipientsException ex) 
    {
        var msg = new StringBuilder();

        for (int k = 0; k < ex.InnerExceptions.Length; k++) 
        {
            var StatusCode = ex.InnerExceptions[k].StatusCode;

            if (StatusCode == SmtpStatusCode.MailboxUnavailable || StatusCode == SmtpStatusCode.MailboxBusy) 
            {
                ErrMsg = "Failed to deliver message to " + ex.FailedRecipient[k].ToString();

                try 
                {
                    if (_TryAgainOnFailure) 
                    {
                        System.Threading.Thread.Sleep(_TryAgainDelayTime);

                        // Send the message
                        string sTemp = "";
                        if (_SendAsync) 
                            Connection.SendAsync(_Email, sTemp);
                        else Connection.Send(_Email);
                    }
                    _ErrMsg = string.Empty;
                } 
                catch (SmtpException sex) 
                {
                    _ErrMsg = sex.Message;
                    _Error = true;
                }
            }
        }
    } 
    catch (SmtpException sex) 
    {
        string dat = sex.Data.ToString();
        _ErrMsg = sex.Message;
        _Error = true;
    }
    return bFlag;
}

如何将该布尔方法转换为异步方法?

我尝试类似的事情:

public async bool Send() {

但是我得到了

  

异步方法的返回类型必须为空,任务或任务

我应该怎么做才能解决这个问题?问候

2 个答案:

答案 0 :(得分:2)

  

异步方法的返回类型必须为voidTaskTask<T>

就像错误状态一样,您必须将返回类型更改为Task<bool>。然后,您将不得不更改方法本身,以使其等待Task或返回Task

public async Task<Boolean> SendAsync() { // renamed your method with suffix Async

    // ... code unchanged
    try {
        await Connection.SendMailAsync(this._Email);
    } 
    // ... code unchanged
}

对于其他调用此方法的方法,它们也应该返回类型Task,除非它们是像Windows窗体或wpf click事件这样的事件驱动的。

另请参阅SendMailAsync

答案 1 :(得分:1)

如果使用Task<T>方法,则必须返回async

您的方法的正确定义是:

public async Task<Boolean> Send()

此外,您还需要在方法内使用await关键字。

您可以使用SendMailAsync编写Send方法。

示例在这里:

public async Task Send(string to, string subject, string body)
{
    var message = new MailMessage
    {
        Subject = subject,
        Body = body
    };
    message.To.Add(to);

    using (var smtpClient = new SmtpClient())
    {
        await smtpClient.SendMailAsync(message);
    }
} 

您可以查看here的更多详细信息。

还请查看有关async/await编程here的详细信息。