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).
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.
CodePudding user response:
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)
Taking into account @phuzi comment on your question it can be that you need to instantiate a client inside your for loop.
Bare in mind that this will use await for you'll have to add async to your function signature.