How to implement a thread queue to run one after the other?

Asked

Viewed 1,055 times

4

I have a static method to record logs on my system.

public class Logger
{
    public static void SaveLog(string[] lines)
    {
        System.IO.File.WriteAllLines(@"C:\...\Temp\ExceptLog.txt", lines);
    }
}

The method is used in several places and access the same text file.

I would like to know how to implement in C# a thread queue to avoid conflict in the requested file access.

How can a thread queue be made to run, one by one in the background, in order to avoid the conflict to concurrent access and thus not "disturb" the main thread?

1 answer

1


Instead of creating a thread queue, why not create a message queue that will be written? So you could have a unique thread that wrote the messages and avoided the access problem, thus creating a producer/consumer system.

The steps, roughly speaking, would be:

  1. Place log write code inside an action;
  2. Put that action in a blocking collection;
  3. Have a thread dedicated to the logging that consumes the blocking collection and perform the actions received, thus ensuring the sequential writing of logs in the file;

An implementation based on the points above:

var LogCollection = new BlockingCollection<Action>();

public static void LogMessage(string messageToLog)
{
    LogCollection.Add(() => File.WriteAllText("", messageToLog));
}

public static void WriteLogMessages(CancellationToken token)
{ 
    foreach (var msg in LogCollection.GetConsumingEnumerable(token))
    {
        msg();
    }
}

Using would look like this:

public static void Main()
{
    using (CancellationTokenSource cts = new CancellationTokenSource())
    {
        Thread t1 = new Thread(() => WriteLogMessages(cts.Token));
        t1.Start();
        LogMessage("Hello World");
        Console.ReadKey();
        cts.Cancel();
        t1.Join();
    }
}

Note: For more ideas, and if you’ve decided to use your own log implementation, take a look at the Nlog for more inspiration.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.