问题描述
我有一个for循环循环通过和发送电子邮件的每个循环。现在即时通讯使用Thread.sleep()方法,但我希望用户仍然能够使用该程序进行交互,只是德拉普一个循环。是否有可能做到这一点,而无需使用了Thread.Sleep?
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 delap that one loop. Is it possible to do this without using thread.sleep?
推荐答案
您运行UI线程的循环?如果是这样,只需使用Task.Factory.StartNew在不同的线程中运行你的循环。如果你需要延时的电子邮件在那个时候发送,放了Thread.Sleep真正开始之前的循环
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.
这将是这个样子:
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);
}
}
这篇关于推迟电子邮件的发送,而无需使用了Thread.Sleep C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!