One thread suspension

I am starting to learn about threads 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

+3


source to share


2 answers


Console is a "thread safe" class, meaning that acces is internally regulated by locks.



With a little (bad) luck, you pause the worker thread in the middle WriteLine()

. Your main thread then pauses when it tries to write and you're stumped.

+5


source


Thread.Suspend

almost always unsafe. This is where you will probably pause the entire console. Imagine that you paused a static constructor system.string

(by accident). Everything will AppDomain

quickly stop.



Use some other ways to sync your streams.

+3


source







All Articles