summaryrefslogtreecommitdiff
path: root/tests/src/baseservices/threading/waithandle/waitany/waitanyex1.cs
blob: b55f8a0fde82d8a0ccdc1c6b6b9be610bbe00877 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Threading;

class WaitAnyEx
{
    private Mutex myMutex;
    private ManualResetEvent myMRE;

    public WaitAnyEx()
    {
        myMutex = new Mutex(false, Common.GetUniqueName());
        myMRE = new ManualResetEvent(false);
    }

    public static int Main()
    {
        WaitAnyEx wae = new WaitAnyEx();
        return wae.Run();
    }

    private int Run()
    {
        int iRet = -1;
        Console.WriteLine("Testing Mutex and non-Mutex, " +
            "not signaling the other element");
        Thread t = new Thread(new ThreadStart(this.AbandonTheMutex));
        t.Start();
        myMRE.WaitOne();
        try
        {
            Console.WriteLine("Waiting...");
            int i = WaitHandle.WaitAny(
                new WaitHandle[]{myMutex,
                new ManualResetEvent(false)}, 10000);
            Console.WriteLine("WaitAny did not throw an " +
                "exception, i = " + i);
        }
        catch(AbandonedMutexException)
        {
            // Expected
            iRet = 100;
        }
        catch(Exception e)
        {
            Console.WriteLine("Unexpected exception thrown: " + 
                e.ToString());
        }
        Console.WriteLine(100 == iRet ? "Test Passed" : "Test Failed");
        return iRet;
    }

    private void AbandonTheMutex()
    {
        Console.WriteLine("Acquire the Mutex");
        myMutex.WaitOne();
        Console.WriteLine("Holding the Mutex");
        // Not calling ReleaseMutex() so the Mutex becomes abandoned
        myMRE.Set();
        Thread.Sleep(1000);
    }
}