Anurag
Anurag

Reputation: 572

Suspend a thread in C#:Error

Am trying to learn threading in C#, right now on a very beginner level. I wrote the below code in order to understand how a thread can be suspended.

But I get the exception 'ThreadStateException was unhandled: Thread is not running.It can not be suspended'

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Thread_Suspend
{
class Program
{
    static void Main(string[] args)
    {
        Thread obj = new Thread(Function1);
        Console.WriteLine("Threading Starts..\n");
        obj.Start();
        Thread.Sleep(2000);
        obj.Suspend();//Exception at this line of code
        Console.WriteLine("Thread suspended");
    }
    static void Function1()
    {
        for (int i = 0; i < 5; i++)
        {
            Console.WriteLine("Thread displayed for: " + i + "time");
        }
        Console.WriteLine("\nThreading done");
    }
}
}

My understanding is that when the console prints 'Thread displayed' for 5 times, the thread will go to sleep for 2000 milliseconds, post which it will go to a suspended state, but it doesn't happen. I am sure I am missing some key concept here. Also, I am using VS 2010 with .NET 4.0 as the targeted framework. Experts please guide here. Any assistance would be highly appreciated.

Regards

Anurag

Upvotes: 1

Views: 287

Answers (2)

AuthorProxy
AuthorProxy

Reputation: 8047

Thread suspended automatically as soon as it finish job. In your case it execute Function1 very fast and suspended automatically.

Upvotes: 0

Jon
Jon

Reputation: 437336

My understanding is that when the console prints 'Thread displayed' for 5 times, the thread will go to sleep for 2000 milliseconds,

No. When the thread prints "5 times" and then "Threading done" it will terminate and cease to exist. The error message complains that you cannot suspend something that does not exist anymore.

What goes to sleep with Thread.Sleep(2000) is your main thread: it starts up the second thread, then goes to sleep for 2 seconds. That's plenty of time for the second thread to complete a 5-iteration loop, so by the time the main thread resumes and calls obj.Suspend the second thread is long since dead.

Upvotes: 3

Related Questions