Home > other >  How to reuse a thread in C#
How to reuse a thread in C#

Time:10-22

I wanted to know how to reuse a thread. I have a websocket connection that constantly sends messages which need some computation to be done. I want to add this computation to a thread, but don't want to create a new thread everytime. How can I make it so that the thread is reused?

client.MsgRecieved.Subscribe(info =>
{
    Thread t = new Thread(() => Do_work(info));
};

Is there a way I can create a thread, name it and then just add Do_work() on that thread?

Edit:

I get multiple messages from the websocket per second. I rather have them wait in a single queue, rather than all run on a new thread.

CodePudding user response:

The simplest pattern is simply

client.MsgRecieved.Subscribe(info =>{
    Task.Run(Do_work(info));
};

Which queues the method to run on the built-in threadpool.

If you want to queue the messages to run on a single background thread, you can use a BlockingCollection, something like:

var workQueue = new System.Collections.Concurrent.BlockingCollection<Object>();
var workThread = new System.Threading.Thread(() =>
{
    foreach (var work in workQueue.GetConsumingEnumerable())
    {
        Do_Work(work);
    }
});

workThread.Start();

then

client.MsgRecieved.Subscribe(info => {
    workQueue.Add(info);
};

CodePudding user response:

You could implement it so the thread never terminates but instead waits for work to do, when finished. You can not start a thread again after it has been terminated.

Example code for a thread class:

internal class WorkerThread
{
    public List<string> textToOutput = new();

    public void MyWorker()
    {
        while (true)
        {
            while (textToOutput.Count <= 0)
            {
                Thread.Sleep(25);
            }
            foreach (var item in textToOutput)
            {
                Console.WriteLine(item);
            }
            textToOutput.Clear();
        }
    }
}

And you could use this as follows:

WorkerThread wt = new WorkerThread();

Thread thread = new Thread(wt.MyWorker);
thread.Start();
Console.WriteLine("Started thread");

wt.textToOutput.Add("Hello world!");

CodePudding user response:

Inject the thread via dependency injection and make it a singleton.

  • Related