Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One thread suspending

I start to learn about threading and I wrote this code.

static void Main(string[] args)
{
    Thread DoAction = new Thread(StartAction);
    DoAction.Start();
    for (int i = 0; i < 10000000; i++)
    {
        Console.WriteLine("Main Thread: {0}", i);
        if (i == 10000) DoAction.Suspend();
    }
}

static void StartAction()
{
    for(int i=0;i<int.MaxValue;++i)
    {
        Console.WriteLine(i);
    }
}

When i==10000 my application stopped. I want to suspend only DoAction Thread

like image 389
user3926523 Avatar asked Aug 09 '26 13:08

user3926523


1 Answers

Console is a 'thread-safe' class meaning that acces is regulated internally with locks.

With a little (bad) luck you will suspend the worker thread in the middle of a WriteLine(). Your main thread is then put on hold when it tries to write, and you're deadlocked.

like image 167
Henk Holterman Avatar answered Aug 11 '26 03:08

Henk Holterman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!