user3926523
user3926523

Reputation: 73

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

Upvotes: 3

Views: 80

Answers (2)

Henk Holterman
Henk Holterman

Reputation: 273179

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.

Upvotes: 5

usr
usr

Reputation: 171178

Thread.Suspend is almost always unsafe. Here, you probably suspend the entire console. Imagine you'd have suspended the static constructor of system.string (by accident). The entire AppDomain would come to a halt quickly.

Use some other means to synchronize your threads.

Upvotes: 3

Related Questions