bbusdriver
bbusdriver

Reputation: 1627

Find a specific thread and access its method C#

I'm trying to find a thread in a list of threads by querying its threadId and access the function in that specific thread.

So when a user inputs price from frontend, it will execute CreateThread() and create a new thread and add it to the thread list.

List<Thread> lstThreads = new List<Thread>();

public static Thread Start(MyClass myClass) {
    Thread thread = new Thread(() => { myClass(); });
    thread.Start();
    return thread;
}

public IActionResult CreateThread(int price) 
{    
    var thread = Start(new MyClass(DoWork(price)));
    lstThreads.Add(thread);
}

public class MyClass 
{
   bool stop = false;

   private void DoWork(int price)
   {
       while(!stop)
       {
           // Do work here
       }

       if (stop) return;
   }

   public void Stop()
   {
       lock (stopLock) {
           stop = true;
       }
   }
}

When a user of the thread now wants to stop the while loop in DoWork() by calling Stop(), how can this be done? User knows the threadId by the way.

Upvotes: 0

Views: 500

Answers (1)

NirolfC
NirolfC

Reputation: 84

First of all, this is such a 1999 approach. If you have the ability to use Tasks and/or async/await do use them! They are far more efficient. Now, if you must use threads you could create/start the thread in MyClass and keep a reference to it then calling Stop on that:

public class MyClass 
{
    private volatile bool stop = false;
    private volatile int price;
    private Thread myThread;

    public MyClass(int price)
    {
        this.price = price;
        myThread = new Thread(DoWork);
    }

    public void DoWork()
    {
        while(!stop)
        {
            // Do work here
        }

        if (stop) return;
    }

    public void Stop()
    {
        stop = true;
    }
}

...

List<MyClass> lstMyThreads = new List<MyClass>();
foreach (var myT in lstMyThreads)
    myT.Stop();

But I need to say this again: if possible use Tasks and CancellationToken.

Upvotes: 1

Related Questions