madan
madan

Reputation: 783

What is the best way to handle a thread from a different thread?

My requirement is to handle a thread from a different thread. I am able to do with thread.Suspend(), thread.Resume() and thread.Abort() but I am getting a warning like these methods has been deprecated. Is there any alternative to these methods, I created a dummy console application which is similar to my application please help to to fix this. Below is my code

using System;
using System.Threading;

namespace ThreadingTest
{
    internal class Program
    {
        private static Thread mainThread;

        private static void Main(string[] args)
        {
            mainThread = Thread.CurrentThread;

            Thread connectServerThread = new Thread(new ThreadStart(ConnectServer));
            connectServerThread.Start();

            int i = 0;
            while (true)
            {
                if (i++ % 5000 == 0)
                {
                    Console.WriteLine(i);
                }
            }
        }

        private static void ConnectServer()
        {
            for (int i = 0; i < 20; i++)
            {
                Thread.Sleep(2000);
                if (i % 2 == 0)
                {
                    mainThread.Suspend();
                }
                else
                {
                    mainThread.Resume();
                }
            }
            mainThread.Abort();
        }
    }
}

Upvotes: 0

Views: 125

Answers (1)

devb
devb

Reputation: 279

I would follow the advice in the documentation

Do not use the Suspend and Resume methods to synchronize the activities of threads. You have no way of knowing what code a thread is executing when you suspend it. If you suspend a thread while it holds locks during a security permission evaluation, other threads in the AppDomain might be blocked. If you suspend a thread while it is executing a class constructor, other threads in the AppDomain that attempt to use that class are blocked. Deadlocks can occur very easily.

And more specifically, the advice the warning provides:

Please use other classes in System.Threading, such as Monitor, Mutex, Event, and Semaphore, to synchronize Threads or protect resources

Upvotes: 1

Related Questions