ASP.NET Controller: An asynchronous module or handler completed while an asynchronous operation was still pending

后端 未结 8 1100
一个人的身影
一个人的身影 2020-11-28 09:36

I have a very simple ASP.NET MVC 4 controller:

public class HomeController : Controller
{
    private const string MY_URL = \"http://smthing\";
    private r         


        
相关标签:
8条回答
  • 2020-11-28 10:30

    The method myWebClient.DownloadStringTaskAsync runs on a separate thread and is non-blocking. A possible solution is to do this with the DownloadDataCompleted event handler for myWebClient and a SemaphoreSlim class field.

    private SemaphoreSlim signalDownloadComplete = new SemaphoreSlim(0, 1);
    private bool isDownloading = false;
    

    ....

    //Add to DownloadAsync() method
    myWebClient.DownloadDataCompleted += (s, e) => {
     isDownloading = false;
     signalDownloadComplete.Release();
    }
    isDownloading = true;
    

    ...

    //Add to block main calling method from returning until download is completed 
    if (isDownloading)
    {
       await signalDownloadComplete.WaitAsync();
    }
    
    0 讨论(0)
  • 2020-11-28 10:30

    Email notification Example With Attachment ..

    public async Task SendNotification(string SendTo,string[] cc,string subject,string body,string path)
        {             
            SmtpClient client = new SmtpClient();
            MailMessage message = new MailMessage();
            message.To.Add(new MailAddress(SendTo));
            foreach (string ccmail in cc)
                {
                    message.CC.Add(new MailAddress(ccmail));
                }
            message.Subject = subject;
            message.Body =body;
            message.Attachments.Add(new Attachment(path));
            //message.Attachments.Add(a);
            try {
                 message.Priority = MailPriority.High;
                message.IsBodyHtml = true;
                await Task.Yield();
                client.Send(message);
            }
            catch(Exception ex)
            {
                ex.ToString();
            }
     }
    
    0 讨论(0)
提交回复
热议问题