I have one button and when I click on it, I am creating one thread and after 10 seconds I am aborting it. When I click on the button again it creates new thread, but the issue is when I use AWAIT, the thread is not aborted. Application is showing old thread's value with newly created thread. But when I am not using AWAIT, it's working fine. Below is just example of my Code.
Logic with AWAIT (you can see in the below image that old thread is also running)
try
{
var _Thread1 = new Thread(async () =>
{
int i = new Random().Next(10, 99);
while (true)
{
this.BeginInvoke(new Action(() =>
{
listBox1.Items.Add($"{i}");
}));
await Task.Delay(3000);
}
});
_Thread1.Start();
Thread.Sleep(10000);
_Thread1.Abort();
}
catch (Exception ex)
{
}
OUTPUT 48 48 48 48 48 48 83 48 83 48 83 48 83
Logic Without Await (below logic works file).
try
{
var _Thread1 = new Thread(async () =>
{
int i = new Random().Next(10, 99);
while (true)
{
this.BeginInvoke(new Action(() =>
{
listBox1.Items.Add($"{i}");
}));
Thread.Sleep(3000);
//await Task.Delay(3000);
}
});
_Thread1.Start();
Thread.Sleep(10000);
_Thread1.Abort();
}
catch (Exception ex)
{
}
OUTPUT. 98 98 98 98 79 79 79 79
I want to abort the thread when it's using AWAIT also.
I can do with CancellationToken/Task, but is there any other way? I want to know why thread is not aborted when AWAIT is used.
Thank you in advance. :)