-1

I have 3 seperate project . Named as

  1. SharedData -> Class Library
  2. Thread 1 -> Window application
  3. Thread 2 -> Console Application

SharedData contains the following 2 functions:

public class SharedData
{
    static private Mutex mut = new Mutex();

    public static void PrintNumbersMutex()
    {

        mut.WaitOne();
        for (int i = 0; i < 500000000; i++)
        {
            Console.WriteLine(" i = " + i);
        }
        mut.ReleaseMutex();
    }
}

Thread1:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        SharedData.DataHolder.PrintNumbersMutex();
    }
}

Thread 2:

public class User2
{
    static void Main(string[] args)
    {
        SharedData.DataHolder.PrintNumbersMutex();
        Console.ReadKey();
    }
}

Thread 1 and Thread 2 are using SharedData library. I have started both project at same time . As I have used lock and mutex still both project are able to call shared function differently. My problem is if one project is executing shared function other should wait. But it doesn't happening . What is problem could you tell me please.

TheLethalCoder
  • 6,668
  • 6
  • 34
  • 69
  • 2
    You need to show us how you instantiate your mutex – TheLethalCoder Jan 06 '17 at 10:10
  • 2
    "I have started both project at same time." That sounds like they're separate *processes* then... so are they using the same global mutex? Just a C# lock won't work, as that's within the process... Fundamentally, we need a [mcve]. (Just a single console app would be fine - it can be launched twice...) – Jon Skeet Jan 06 '17 at 10:12
  • How to define global mutex? – sarita sirsat Jan 06 '17 at 10:15
  • As far as I can see this is a dupe of http://stackoverflow.com/questions/229565/what-is-a-good-pattern-for-using-a-global-mutex-in-c which has a very nice answer – tolanj Jan 06 '17 at 10:29

1 Answers1

1

You need to use a global mutex:

string mutexId;
if (useGlobal) //Here global refers to across users on that machine
{
    mutexId = String.Format("Global\\{{{0}}}", _appGuid);
}
else
{
    mutexId = String.Format("{{{0}}}", _appGuid);
}

The above example uses the applications GUID, from the assembly information for single instancing the app. You can use any unique string though so something like:

mutexId = String.Format("{{{0}}}", "MyUniqueString");

You define your mutex as:

private static Mutex _mutex;

And instantiate it as:

_mutex = new Mutex(false, mutexId);

You can then use the mutex in your method:

try
{
    if (_mutex.WaitOne(timeOut, false))
    {
        //Process
        _mutex.RealeaseMutex();
    }
    else
    {
        //Handle not receiving the mutex
    }
}
catch (AbandonedMutexException)
{
    //Handle
}
TheLethalCoder
  • 6,668
  • 6
  • 34
  • 69