delaying the sending of email messages without using Thread.Sleep c#

后端 未结 4 1707
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-29 04:14

I have a for loop which loops through and sends an email each loop. Right now im using thread.sleep() but I want the user to still be able to interact with the program, just del

相关标签:
4条回答
  • 2021-01-29 04:50

    You can spin off a new thread to send the emails so you don't lock the UI thread.

    0 讨论(0)
  • 2021-01-29 04:50

    Try shifting the code to background Thread.

    0 讨论(0)
  • 2021-01-29 05:08

    You need to put the method of sending mail in separated thread to keep your GUI interactive .

    Thread newThread = new Thread(new ThreadStart(SendMail));
    newThread.Start();
    
    public void SendMail() 
    {
        //Send mails here       
    }
    
    0 讨论(0)
  • 2021-01-29 05:09

    Are you running the loop on the UI thread? If so, just use Task.Factory.StartNew to run your loop in a different thread. If you need to delay the email sending at that time, put a Thread.Sleep before you actually begin looping.

    It will look something like this:

    private void OnButtonClick(object sender, EventArgs e)
    {
        //This code happens on the UI thread
        Task.Factory.StartNew(SendEmails);
    }
    
    private void SendEmails()
    {
        Thread.Sleep(500);
    
        foreach(var email in emailAddresses) {
            SendEmail(email);
        }
    }
    
    0 讨论(0)
提交回复
热议问题