How to correctly implement a System.Threading.Monitor in . net core

Asked

Viewed 15 times

1

I have a piece of code that implements a Monitor. The purpose of this code is not to allow another thread to write in the log while one of them is running.

This code works perfectly in . net framework 4.5, but I don’t get the same result in . net core.

Here the class that implements the Monitor:

public class Locker
{
    private static bool _entered = false;
    private static readonly object _lock = new object();

    public void LockOn(TimeSpan timeOut, Action method)
    {
        try
        {
            if (!Monitor.TryEnter(_lock, timeOut))
                throw new TimeoutException("Não foi possível adquirir lock no tempo especificado");

            _entered = true;
            method();

        }
        finally
        {
            if (_entered)
            {
                Monitor.Exit(_lock);
            }
        }

    }
}

Here the use of it:

static void Main(string[] args)
{
    const int ITERATIONS = 5;
    Locker locker = new Locker();
    StringBuilder log = new StringBuilder();

    Parallel.ForEach(new string[] { "A", "B" }, (string taskName) =>
    {
        for (int i = 0; i < ITERATIONS; ++i)
        {
            locker.LockOn(TimeSpan.FromSeconds(10), () =>
            {
                //nosso amigo "A" faz sleep de 50ms, enquanto o "B" faz sleep de 100ms
                TimeSpan sleepTime = taskName == "A" ? TimeSpan.FromMilliseconds(50) : TimeSpan.FromMilliseconds(100);
                Task.Delay(sleepTime).Wait();

                log.Append(taskName);
            });
        }
    });

    string finalLog = log.ToString();
    Console.WriteLine(finalLog);
    Console.ReadKey();
}

Running in . net framework I get the following result:

ABABABABAB

But in . net core I can’t get this same result... What could be wrong? I have tried running from . net core 2.0, 2.1 and 3.1..

No answers

Browser other questions tagged

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