简体   繁体   English

我想在控制台应用程序中使用 smtp 一次发送多个 email 请求。如何使用线程一次发送批量 email 请求

[英]I want to send multiple email request at a time using smtp in console application .how I can send bulk email request at a time with using threading

for (int i = 0; i < 50; i++)
{
    Thread T1 = new Thread(delegate ()
    {
            Console.WriteLine("email sent..");
            smtp.Send(msg);
    });
    T1.Start();
}                       

I am trying to send bulk request with multithreading using smtp.Send(msg).我正在尝试使用 smtp.Send(msg) 通过多线程发送批量请求。

I have tried the code above but I am getting this error我已经尝试了上面的代码,但出现了这个错误

An asynchronous call is already in progress.异步调用已在进行中。 It must be completed or canceled before you can call this method必须先完成或取消才能调用此方法

How I can resolve this.我该如何解决这个问题。

If you are using following client .如果您使用以下客户端 I would recommend you refactor your code like following:我建议您重构您的代码,如下所示:

var tasks = new List<Task>()
for (int i = 0; i < 50; i++)
{
    task.Add(smtp.SendAsync(msg));
}
await Task.WhenAll(tasks)

What's the difference?有什么不同?

Using tasks will use Threads in the background but will take care of all the thread scheduling and cleanup.使用任务将在后台使用线程,但会负责所有线程调度和清理。 c# TPL is the way to go if you want to add parallelism and concurrency to your application applications (I stole that line from above link) c# TPL是通往 go 的途径,如果你想为你的应用程序添加并行性和并发性(我从上面的链接中偷走了那一行)

Taking into account @phuzi comment on your question it can be that you need to instantiate a client inside your for loop.考虑到@phuzi 对您的问题的评论,您可能需要在 for 循环中实例化一个客户端。

Bare in mind that this will use await for you'll have to add async to your function signature.请记住,这将使用等待,因为您必须将异步添加到您的 function 签名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM