AutoresetEvent and Singleton Problem

Can someone please tell me what is wrong with the following code? Ideally, he should first start the stream, and then wait for the set event. Instead, it does not start the thread and just loops on WaitOne ().

I am interested to know what happened to the thread and why?

class Program
{   
    static void Main(string[] args)
    {
        Testing t = Testing.Instance;
        Console.Read();
    }
}


class Testing
{
    private static AutoResetEvent evt = new AutoResetEvent(false);
    public static Testing Instance = new Testing();

    private Testing()
    {
        Create();
        evt.WaitOne();
        Console.WriteLine("out");
    }

    private void Create()
    {
        Console.WriteLine("Starting thread");
        new Thread(Print).Start();
    }

    private void Print()
    {
        Console.WriteLine("started");
        evt.Set();
    }
}

EDIT: So far, the description provided by @BrokenGlass makes sense. but changing the code to the following code allows another thread to access instance methods without completing the constructor. (Suggested by @NicoSchertler).

private static Testing _Instance;

public static Testing Instance
{
get
{
    if (_Instance == null)
        _Instance = new Testing();
    return _Instance;
}
}
+3
source share
3 answers

, , Print , , - , , Print.

evt.WaitOne() Thread.Sleep() - , - .

+5

, . , , , .

singleton . .

private static Testing _Instance;

public static Testing Instance
{
    get
    {
        if (_Instance == null)
            _Instance = new Testing();
        return _Instance;
    }
}

, evt. .

+3

My guess would be a problem with the relative initialization time of the static field. Try initializing evtin the constructor Testinginstead:

private static AutoResetEvent evt;
public static Testing Instance = new Testing();

private Testing()
{
    evt = new AutoResetEvent(false);
    Create();
    evt.WaitOne();
    Console.WriteLine("out");
}

I should note that this is really just an assumption - I would have thought that this code would work fine.

0
source

All Articles