Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Mutex Not Working

Mutex Not Working

Scheduled Pinned Locked Moved C#
helpcsharphtmlcomdata-structures
23 Posts 4 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • D Offline
    D Offline
    Dwayner79
    wrote on last edited by
    #1

    I am trying to track down a problem with communications and began using Mutex to combate the problem. I have various functions that each call the same Mutex: public bool function1() { Mutex mutex = new Mutex(false, "MyMutex"); mutex.WaitOne(); Console.WriteLine("mutex entered"); //Do work Console.WriteLine("mutex exiteded"); mutex.ReleaseMutex(); return Give_Status; } public bool function2() { Mutex mutex = new Mutex(false, "MyMutex"); mutex.WaitOne(); Console.WriteLine("mutex entered"); //Do work Console.WriteLine("mutex exiteded"); mutex.ReleaseMutex(); return Give_Status; } According to c#Help you can call it this way and as long as it has the same name, it will work. It is not working however. Here is a sample of the output. mutex exited 8/8/2005 12:47:08 PM Enter WriteStream byte[]:System.Byte[],False 8/8/2005 12:47:08 PM Enter WriteBuffer mutex entered DummyValue 8/8/2005 12:47:08 PM Leaving WriteStream byte[]:True 8/8/2005 12:47:08 PM Enter ReadStream byte[]:5 8/8/2005 12:47:08 PM Enter readBuffer 8/8/2005 12:47:08 PM Leaving ReadStream:System.Byte[] 8/8/2005 12:47:08 PM Enter Flush() 8/8/2005 12:47:08 PM Clear Write Req. Queue = 0 8/8/2005 12:47:08 PM Clear Read Req. Queue = 0 8/8/2005 12:47:08 PM Leaving Flush() 8/8/2005 12:47:08 PM Enter WriteStream byte[]:System.Byte[],False 8/8/2005 12:47:08 PM Enter WriteBuffer mutex exited mutex entered DummyValue 8/8/2005 12:47:08 PM Leaving WriteStream byte[]:True 8/8/2005 12:47:08 PM Enter ReadStream byte[]:5 8/8/2005 12:47:08 PM Enter readBuffer 8/8/2005 12:47:08 PM Leaving ReadStream:System.Byte[] 8/8/2005 12:47:08 PM Enter Flush() 8/8/2005 12:47:08 PM Clear Write Req. Queue = 0 8/8/2005 12:47:08 PM Clear Read Req. Queue = 0 8/8/2005 12:47:08 PM Leaving Flush() 8/8/2005 12:47:08 PM Enter WriteStream byte[]:System.Byte[],False 8/8/2005 12:47:08 PM Enter WriteBuffer 8/8/2005 12:47:08 PM Leaving WriteStream byte[]:True mutex exited mutex entered DummyValue mutex entered Notice on the end here, I entered mutex without exiting!!!! Any idea what would be causing this. ***************** "We need to apply 21st-century information technology to the health care field. We need to have our medical records put on the I.T." —GW

    G J 3 Replies Last reply
    0
    • D Dwayner79

      I am trying to track down a problem with communications and began using Mutex to combate the problem. I have various functions that each call the same Mutex: public bool function1() { Mutex mutex = new Mutex(false, "MyMutex"); mutex.WaitOne(); Console.WriteLine("mutex entered"); //Do work Console.WriteLine("mutex exiteded"); mutex.ReleaseMutex(); return Give_Status; } public bool function2() { Mutex mutex = new Mutex(false, "MyMutex"); mutex.WaitOne(); Console.WriteLine("mutex entered"); //Do work Console.WriteLine("mutex exiteded"); mutex.ReleaseMutex(); return Give_Status; } According to c#Help you can call it this way and as long as it has the same name, it will work. It is not working however. Here is a sample of the output. mutex exited 8/8/2005 12:47:08 PM Enter WriteStream byte[]:System.Byte[],False 8/8/2005 12:47:08 PM Enter WriteBuffer mutex entered DummyValue 8/8/2005 12:47:08 PM Leaving WriteStream byte[]:True 8/8/2005 12:47:08 PM Enter ReadStream byte[]:5 8/8/2005 12:47:08 PM Enter readBuffer 8/8/2005 12:47:08 PM Leaving ReadStream:System.Byte[] 8/8/2005 12:47:08 PM Enter Flush() 8/8/2005 12:47:08 PM Clear Write Req. Queue = 0 8/8/2005 12:47:08 PM Clear Read Req. Queue = 0 8/8/2005 12:47:08 PM Leaving Flush() 8/8/2005 12:47:08 PM Enter WriteStream byte[]:System.Byte[],False 8/8/2005 12:47:08 PM Enter WriteBuffer mutex exited mutex entered DummyValue 8/8/2005 12:47:08 PM Leaving WriteStream byte[]:True 8/8/2005 12:47:08 PM Enter ReadStream byte[]:5 8/8/2005 12:47:08 PM Enter readBuffer 8/8/2005 12:47:08 PM Leaving ReadStream:System.Byte[] 8/8/2005 12:47:08 PM Enter Flush() 8/8/2005 12:47:08 PM Clear Write Req. Queue = 0 8/8/2005 12:47:08 PM Clear Read Req. Queue = 0 8/8/2005 12:47:08 PM Leaving Flush() 8/8/2005 12:47:08 PM Enter WriteStream byte[]:System.Byte[],False 8/8/2005 12:47:08 PM Enter WriteBuffer 8/8/2005 12:47:08 PM Leaving WriteStream byte[]:True mutex exited mutex entered DummyValue mutex entered Notice on the end here, I entered mutex without exiting!!!! Any idea what would be causing this. ***************** "We need to apply 21st-century information technology to the health care field. We need to have our medical records put on the I.T." —GW

      G Offline
      G Offline
      Guffa
      wrote on last edited by
      #2

      The code and the result does not match. In the code you use the typo "exiteded", but that is not present in the output. How much more have you changed in the code before you ran it to create the output? You might think that I am picky, but I have several times spent time to find peoples errors where there were none, in code that was not even used... --- b { font-weight: normal; }

      D 1 Reply Last reply
      0
      • G Guffa

        The code and the result does not match. In the code you use the typo "exiteded", but that is not present in the output. How much more have you changed in the code before you ran it to create the output? You might think that I am picky, but I have several times spent time to find peoples errors where there were none, in code that was not even used... --- b { font-weight: normal; }

        D Offline
        D Offline
        Dwayner79
        wrote on last edited by
        #3

        The output is a copy paste... the code I tried to simplify. Here is a copy paste from one of the functions (no changes) public bool commandExitServiceMode() { Mutex mutex = new Mutex(false, "MyMutex"); mutex.WaitOne(); Console.WriteLine("mutex entered"); if ( OpenPort() == false ) Give_Status = false; else { Give_Status = false; byteToSend = new byte[3]; byteToSend[0] = CMDEXITSERVICEMODE; sum_xmit_bfr(0); if(sendAndGetData(3,5)) Give_Status = true; else { MessageBox.Show("Command Fail received from PCC-III to ExitServiceMode"); Give_Status = false; } } Console.WriteLine("mutex exited"); mutex.ReleaseMutex(); return Give_Status; } There are about 10 of these different ones, all have the opening and closing mutex related lines. ***************** "We need to apply 21st-century information technology to the health care field. We need to have our medical records put on the I.T." —GW

        S 1 Reply Last reply
        0
        • D Dwayner79

          The output is a copy paste... the code I tried to simplify. Here is a copy paste from one of the functions (no changes) public bool commandExitServiceMode() { Mutex mutex = new Mutex(false, "MyMutex"); mutex.WaitOne(); Console.WriteLine("mutex entered"); if ( OpenPort() == false ) Give_Status = false; else { Give_Status = false; byteToSend = new byte[3]; byteToSend[0] = CMDEXITSERVICEMODE; sum_xmit_bfr(0); if(sendAndGetData(3,5)) Give_Status = true; else { MessageBox.Show("Command Fail received from PCC-III to ExitServiceMode"); Give_Status = false; } } Console.WriteLine("mutex exited"); mutex.ReleaseMutex(); return Give_Status; } There are about 10 of these different ones, all have the opening and closing mutex related lines. ***************** "We need to apply 21st-century information technology to the health care field. We need to have our medical records put on the I.T." —GW

          S Offline
          S Offline
          S Senthil Kumar
          wrote on last edited by
          #4

          Maybe one of your Mutex protected functions called another Mutex protected one? Because they are on the same thread, the mutex won't block and you'll enter the mutex immediately. Or maybe there is a typo in one of your Mutex constructors that causes a new Mutex to be created? That aside, are these functions spread across processes? Mutexes are heavyweight, so I'd prefer Monitor.Enter and Exit, unless of course synchronization needs to be cross process. Regards Senthil _____________________________ My Blog | My Articles | WinMacro

          D 1 Reply Last reply
          0
          • D Dwayner79

            I am trying to track down a problem with communications and began using Mutex to combate the problem. I have various functions that each call the same Mutex: public bool function1() { Mutex mutex = new Mutex(false, "MyMutex"); mutex.WaitOne(); Console.WriteLine("mutex entered"); //Do work Console.WriteLine("mutex exiteded"); mutex.ReleaseMutex(); return Give_Status; } public bool function2() { Mutex mutex = new Mutex(false, "MyMutex"); mutex.WaitOne(); Console.WriteLine("mutex entered"); //Do work Console.WriteLine("mutex exiteded"); mutex.ReleaseMutex(); return Give_Status; } According to c#Help you can call it this way and as long as it has the same name, it will work. It is not working however. Here is a sample of the output. mutex exited 8/8/2005 12:47:08 PM Enter WriteStream byte[]:System.Byte[],False 8/8/2005 12:47:08 PM Enter WriteBuffer mutex entered DummyValue 8/8/2005 12:47:08 PM Leaving WriteStream byte[]:True 8/8/2005 12:47:08 PM Enter ReadStream byte[]:5 8/8/2005 12:47:08 PM Enter readBuffer 8/8/2005 12:47:08 PM Leaving ReadStream:System.Byte[] 8/8/2005 12:47:08 PM Enter Flush() 8/8/2005 12:47:08 PM Clear Write Req. Queue = 0 8/8/2005 12:47:08 PM Clear Read Req. Queue = 0 8/8/2005 12:47:08 PM Leaving Flush() 8/8/2005 12:47:08 PM Enter WriteStream byte[]:System.Byte[],False 8/8/2005 12:47:08 PM Enter WriteBuffer mutex exited mutex entered DummyValue 8/8/2005 12:47:08 PM Leaving WriteStream byte[]:True 8/8/2005 12:47:08 PM Enter ReadStream byte[]:5 8/8/2005 12:47:08 PM Enter readBuffer 8/8/2005 12:47:08 PM Leaving ReadStream:System.Byte[] 8/8/2005 12:47:08 PM Enter Flush() 8/8/2005 12:47:08 PM Clear Write Req. Queue = 0 8/8/2005 12:47:08 PM Clear Read Req. Queue = 0 8/8/2005 12:47:08 PM Leaving Flush() 8/8/2005 12:47:08 PM Enter WriteStream byte[]:System.Byte[],False 8/8/2005 12:47:08 PM Enter WriteBuffer 8/8/2005 12:47:08 PM Leaving WriteStream byte[]:True mutex exited mutex entered DummyValue mutex entered Notice on the end here, I entered mutex without exiting!!!! Any idea what would be causing this. ***************** "We need to apply 21st-century information technology to the health care field. We need to have our medical records put on the I.T." —GW

            J Offline
            J Offline
            jan larsen
            wrote on last edited by
            #5

            As S. Senthil Kumar says, there could be a typo somewhere in a mutex construction. This is one of the places where the use of a constant would be a Good Thing. Another thing: I don't know if you've taken care of errors in your methods, but I definately would use a construct like this:

            public sealed class MyClass
            {
            public static readonly string MUTEX_ID = "MyMutex";

            private readonly Mutex myMutex;

            public MyClass()
            {
            myMutex = new Mutex(false, MUTEX_ID);
            }

            internal void Foo()
            {
            myMutex.WaitOne();
            try
            {
            // This is where to handle the critical stuff...
            }
            finally
            {
            myMutex.ReleaseMutex();
            }
            }

            }

            "God doesn't play dice" - Albert Einstein "God not only plays dice, He sometimes throws the dices where they cannot be seen" - Niels Bohr

            D 1 Reply Last reply
            0
            • S S Senthil Kumar

              Maybe one of your Mutex protected functions called another Mutex protected one? Because they are on the same thread, the mutex won't block and you'll enter the mutex immediately. Or maybe there is a typo in one of your Mutex constructors that causes a new Mutex to be created? That aside, are these functions spread across processes? Mutexes are heavyweight, so I'd prefer Monitor.Enter and Exit, unless of course synchronization needs to be cross process. Regards Senthil _____________________________ My Blog | My Articles | WinMacro

              D Offline
              D Offline
              Dwayner79
              wrote on last edited by
              #6

              I have verified that no errors in typing the construct of the Mutex. I also verified that no function calls another mutex controlled function. However, you may be on to something. In the last go around with this, I am calling the same function 4-5 times. The idea is something like: for(int i=1; i<5; i++) { public bool mutexControlledFunction(); } mutexControlledFunction() { Mutex mutex = new Mutex(false, "MyMutex"); mutex.WaitOne(); Console.WriteLine("mutex entered"); //Do stuff here Console.WriteLine("mutex exited"); mutex.ReleaseMutex(); return Give_Status; } There was one early return that I put a breakpoint on to verify that is never ran (it did not) so I know all of the mutex.ReleaseMutex() were run. My understanding is this is the way Mutex is supposed to work. I know that there can not be a typo, because it is calling the same function. Also, I went with Mutex because it can be declared in multiple places and work together. I am not sure if Monitor has the same functionality. I have about ten functions that all need to be able to wait for the right to process. Only one of these ten can be running at the same time. If there is a better way to do this, I am open to suggestions. Thanks so much, Dwayne ***************** "We need to apply 21st-century information technology to the health care field. We need to have our medical records put on the I.T." —GW

              1 Reply Last reply
              0
              • J jan larsen

                As S. Senthil Kumar says, there could be a typo somewhere in a mutex construction. This is one of the places where the use of a constant would be a Good Thing. Another thing: I don't know if you've taken care of errors in your methods, but I definately would use a construct like this:

                public sealed class MyClass
                {
                public static readonly string MUTEX_ID = "MyMutex";

                private readonly Mutex myMutex;

                public MyClass()
                {
                myMutex = new Mutex(false, MUTEX_ID);
                }

                internal void Foo()
                {
                myMutex.WaitOne();
                try
                {
                // This is where to handle the critical stuff...
                }
                finally
                {
                myMutex.ReleaseMutex();
                }
                }

                }

                "God doesn't play dice" - Albert Einstein "God not only plays dice, He sometimes throws the dices where they cannot be seen" - Niels Bohr

                D Offline
                D Offline
                Dwayner79
                wrote on last edited by
                #7

                Thanks for the reply. Please see my post above as there are some more questions. Again, thanks for the help. ***************** "We need to apply 21st-century information technology to the health care field. We need to have our medical records put on the I.T." —GW

                J 1 Reply Last reply
                0
                • D Dwayner79

                  Thanks for the reply. Please see my post above as there are some more questions. Again, thanks for the help. ***************** "We need to apply 21st-century information technology to the health care field. We need to have our medical records put on the I.T." —GW

                  J Offline
                  J Offline
                  jan larsen
                  wrote on last edited by
                  #8

                  If there isn't a typo, then I don't see where the bug is. But, if you're not concerned about process synchronization and you need mutual exclusion, then you can use the lock keyword:

                  public class SomeClass
                  {
                  public static readonly object LOCK_OBJECT = new object();
                  }

                  public class MyFirstClass
                  {
                  public void Foo()
                  {
                  lock(SomeClass.LOCK_OBJECT)
                  {
                  // This is where to put your synchronized code.
                  }
                  }
                  }

                  public class MySecondClass
                  {
                  public void Bar()
                  {
                  lock(SomeClass.LOCK_OBJECT)
                  {
                  // This is where to put your synchronized code.
                  }
                  }
                  }

                  This approach is much faster and cleaner. "God doesn't play dice" - Albert Einstein "God not only plays dice, He sometimes throws the dices where they cannot be seen" - Niels Bohr

                  D 1 Reply Last reply
                  0
                  • J jan larsen

                    If there isn't a typo, then I don't see where the bug is. But, if you're not concerned about process synchronization and you need mutual exclusion, then you can use the lock keyword:

                    public class SomeClass
                    {
                    public static readonly object LOCK_OBJECT = new object();
                    }

                    public class MyFirstClass
                    {
                    public void Foo()
                    {
                    lock(SomeClass.LOCK_OBJECT)
                    {
                    // This is where to put your synchronized code.
                    }
                    }
                    }

                    public class MySecondClass
                    {
                    public void Bar()
                    {
                    lock(SomeClass.LOCK_OBJECT)
                    {
                    // This is where to put your synchronized code.
                    }
                    }
                    }

                    This approach is much faster and cleaner. "God doesn't play dice" - Albert Einstein "God not only plays dice, He sometimes throws the dices where they cannot be seen" - Niels Bohr

                    D Offline
                    D Offline
                    Dwayner79
                    wrote on last edited by
                    #9

                    These functions are return type bool. If I return from inside the lock will it unlock? thanks again.: public class MyFirstClass { public bool Foo() { lock(SomeClass.LOCK_OBJECT) { // This is where to put your synchronized code. return some_bool; //return HERE????????? } return some_bool; // OR return HERE????? } } ***************** "We need to apply 21st-century information technology to the health care field. We need to have our medical records put on the I.T." —GW

                    J 1 Reply Last reply
                    0
                    • D Dwayner79

                      These functions are return type bool. If I return from inside the lock will it unlock? thanks again.: public class MyFirstClass { public bool Foo() { lock(SomeClass.LOCK_OBJECT) { // This is where to put your synchronized code. return some_bool; //return HERE????????? } return some_bool; // OR return HERE????? } } ***************** "We need to apply 21st-century information technology to the health care field. We need to have our medical records put on the I.T." —GW

                      J Offline
                      J Offline
                      jan larsen
                      wrote on last edited by
                      #10

                      Dwayner79 wrote: If I return from inside the lock will it unlock? Yes. "God doesn't play dice" - Albert Einstein "God not only plays dice, He sometimes throws the dices where they cannot be seen" - Niels Bohr

                      D 1 Reply Last reply
                      0
                      • J jan larsen

                        Dwayner79 wrote: If I return from inside the lock will it unlock? Yes. "God doesn't play dice" - Albert Einstein "God not only plays dice, He sometimes throws the dices where they cannot be seen" - Niels Bohr

                        D Offline
                        D Offline
                        Dwayner79
                        wrote on last edited by
                        #11

                        OK. Here is what I have: public class LockClass { public static readonly object LOCK_OBJECT = new object(); } <\code> In another class in the same namespace: `public bool commandUnForceAll() { lock(LockClass.LOCK_OBJECT) { if ( OpenPort() == false ) Give_Status = false; else { Give_Status = false; byteToSend = new byte[3]; byteToSend[0] = CMDUNFORCEALL; sum_xmit_bfr (0); if (sendAndGetData(3, 5)) Give_Status = true; else { MessageBox.Show("Command Fail received from PCC-III to CommandUnForceAll()"); Give_Status = false; } } } return Give_Status; } public bool commandForceBlockOutput(int block, int blockOutput) { lock(LockClass.LOCK_OBJECT) { if ( block < 3) { MessageBox.Show(this, "Cannot Force blocks 0-3"); return false; } if ( OpenPort() == false ) Give_Status = false; else { Give_Status = false; byteToSend = new byte[6]; byteToSend[0] = CMDFORCEBLOCKOUTPUT; byteToSend[1] = Convert.ToByte(block); byteToSend[2] = Convert.ToByte(((blockOutput & -256) / 256) & 255); byteToSend[3] = Convert.ToByte(blockOutput & 255); sum_xmit_bfr(3); if (sendAndGetData(6,5)) Give_Status = true; else { MessageBox.Show("Command Fail received from PCC-III to CommandForceBlockOutput(" + block + ")"); Give_Status = false; } } } return Give_Status; }` I am at a lost as to why this will not work. I am so very greatful for all your help. ***************** "We need to apply 21st-century information technology to the health care field. We need to have our medical records put on the I.T." —GW

                        J 1 Reply Last reply
                        0
                        • D Dwayner79

                          I am trying to track down a problem with communications and began using Mutex to combate the problem. I have various functions that each call the same Mutex: public bool function1() { Mutex mutex = new Mutex(false, "MyMutex"); mutex.WaitOne(); Console.WriteLine("mutex entered"); //Do work Console.WriteLine("mutex exiteded"); mutex.ReleaseMutex(); return Give_Status; } public bool function2() { Mutex mutex = new Mutex(false, "MyMutex"); mutex.WaitOne(); Console.WriteLine("mutex entered"); //Do work Console.WriteLine("mutex exiteded"); mutex.ReleaseMutex(); return Give_Status; } According to c#Help you can call it this way and as long as it has the same name, it will work. It is not working however. Here is a sample of the output. mutex exited 8/8/2005 12:47:08 PM Enter WriteStream byte[]:System.Byte[],False 8/8/2005 12:47:08 PM Enter WriteBuffer mutex entered DummyValue 8/8/2005 12:47:08 PM Leaving WriteStream byte[]:True 8/8/2005 12:47:08 PM Enter ReadStream byte[]:5 8/8/2005 12:47:08 PM Enter readBuffer 8/8/2005 12:47:08 PM Leaving ReadStream:System.Byte[] 8/8/2005 12:47:08 PM Enter Flush() 8/8/2005 12:47:08 PM Clear Write Req. Queue = 0 8/8/2005 12:47:08 PM Clear Read Req. Queue = 0 8/8/2005 12:47:08 PM Leaving Flush() 8/8/2005 12:47:08 PM Enter WriteStream byte[]:System.Byte[],False 8/8/2005 12:47:08 PM Enter WriteBuffer mutex exited mutex entered DummyValue 8/8/2005 12:47:08 PM Leaving WriteStream byte[]:True 8/8/2005 12:47:08 PM Enter ReadStream byte[]:5 8/8/2005 12:47:08 PM Enter readBuffer 8/8/2005 12:47:08 PM Leaving ReadStream:System.Byte[] 8/8/2005 12:47:08 PM Enter Flush() 8/8/2005 12:47:08 PM Clear Write Req. Queue = 0 8/8/2005 12:47:08 PM Clear Read Req. Queue = 0 8/8/2005 12:47:08 PM Leaving Flush() 8/8/2005 12:47:08 PM Enter WriteStream byte[]:System.Byte[],False 8/8/2005 12:47:08 PM Enter WriteBuffer 8/8/2005 12:47:08 PM Leaving WriteStream byte[]:True mutex exited mutex entered DummyValue mutex entered Notice on the end here, I entered mutex without exiting!!!! Any idea what would be causing this. ***************** "We need to apply 21st-century information technology to the health care field. We need to have our medical records put on the I.T." —GW

                          J Offline
                          J Offline
                          jan larsen
                          wrote on last edited by
                          #12

                          I didn't see it before, but there is only on condition I can think of that would give this output (considered that there really isn't a typo).

                          public bool function1()
                          {
                          Mutex mutex = new Mutex(false, "MyMutex");
                          mutex.WaitOne();
                          Console.WriteLine("mutex entered");

                          //Do work
                          // You may be doing something here that throws an exception. If you catch it somewhere
                          // and don't print it, then you will get the output you do.

                          Console.WriteLine("mutex exiteded");
                          mutex.ReleaseMutex();

                          return Give_Status;
                          }

                          "God doesn't play dice" - Albert Einstein "God not only plays dice, He sometimes throws the dices where they cannot be seen" - Niels Bohr

                          D 1 Reply Last reply
                          0
                          • D Dwayner79

                            OK. Here is what I have: public class LockClass { public static readonly object LOCK_OBJECT = new object(); } <\code> In another class in the same namespace: `public bool commandUnForceAll() { lock(LockClass.LOCK_OBJECT) { if ( OpenPort() == false ) Give_Status = false; else { Give_Status = false; byteToSend = new byte[3]; byteToSend[0] = CMDUNFORCEALL; sum_xmit_bfr (0); if (sendAndGetData(3, 5)) Give_Status = true; else { MessageBox.Show("Command Fail received from PCC-III to CommandUnForceAll()"); Give_Status = false; } } } return Give_Status; } public bool commandForceBlockOutput(int block, int blockOutput) { lock(LockClass.LOCK_OBJECT) { if ( block < 3) { MessageBox.Show(this, "Cannot Force blocks 0-3"); return false; } if ( OpenPort() == false ) Give_Status = false; else { Give_Status = false; byteToSend = new byte[6]; byteToSend[0] = CMDFORCEBLOCKOUTPUT; byteToSend[1] = Convert.ToByte(block); byteToSend[2] = Convert.ToByte(((blockOutput & -256) / 256) & 255); byteToSend[3] = Convert.ToByte(blockOutput & 255); sum_xmit_bfr(3); if (sendAndGetData(6,5)) Give_Status = true; else { MessageBox.Show("Command Fail received from PCC-III to CommandForceBlockOutput(" + block + ")"); Give_Status = false; } } } return Give_Status; }` I am at a lost as to why this will not work. I am so very greatful for all your help. ***************** "We need to apply 21st-century information technology to the health care field. We need to have our medical records put on the I.T." —GW

                            J Offline
                            J Offline
                            jan larsen
                            wrote on last edited by
                            #13

                            There is one thing that annoys me :-), and that is your use of a member variable as a return value. When doing that, you take on the burden to be sure that access to that variable is synchronized too. It's just a little thing, but add more of that, and you'll soon end up in a situation where you can't figure out why variable x suddenly changes its value. If you have to use a member variable, be sure to declare it volatile. This ensures that the system doesn't use a cached value for performance reasons, but actually reads the value from the object heap. "God doesn't play dice" - Albert Einstein "God not only plays dice, He sometimes throws the dices where they cannot be seen" - Niels Bohr

                            D 1 Reply Last reply
                            0
                            • J jan larsen

                              I didn't see it before, but there is only on condition I can think of that would give this output (considered that there really isn't a typo).

                              public bool function1()
                              {
                              Mutex mutex = new Mutex(false, "MyMutex");
                              mutex.WaitOne();
                              Console.WriteLine("mutex entered");

                              //Do work
                              // You may be doing something here that throws an exception. If you catch it somewhere
                              // and don't print it, then you will get the output you do.

                              Console.WriteLine("mutex exiteded");
                              mutex.ReleaseMutex();

                              return Give_Status;
                              }

                              "God doesn't play dice" - Albert Einstein "God not only plays dice, He sometimes throws the dices where they cannot be seen" - Niels Bohr

                              D Offline
                              D Offline
                              Dwayner79
                              wrote on last edited by
                              #14

                              To combat this, I wrapped everything into a try catch block. No exceptions thrown. I have changed everything over to the Lock method you suggested. I copied and pasted into the functions and verified no typos. I am at a loss. Thanks for your help. I could post more code if you think it would help. ***************** "We need to apply 21st-century information technology to the health care field. We need to have our medical records put on the I.T." —GW

                              J 1 Reply Last reply
                              0
                              • J jan larsen

                                There is one thing that annoys me :-), and that is your use of a member variable as a return value. When doing that, you take on the burden to be sure that access to that variable is synchronized too. It's just a little thing, but add more of that, and you'll soon end up in a situation where you can't figure out why variable x suddenly changes its value. If you have to use a member variable, be sure to declare it volatile. This ensures that the system doesn't use a cached value for performance reasons, but actually reads the value from the object heap. "God doesn't play dice" - Albert Einstein "God not only plays dice, He sometimes throws the dices where they cannot be seen" - Niels Bohr

                                D Offline
                                D Offline
                                Dwayner79
                                wrote on last edited by
                                #15

                                You are right. I will change that to a local variable. The other thing that bothers me about the code (this is not my code... I just get to troubleshoot/fix it) is this use of byteToSend as a member array. The 10 different functions reinitialize the array to the size needed then call sendAndGetData() which actually writes to a controller via the serial port. Instead of passing these values to sendAndGetData, it is a member variable. I have not figured out the best way around this. But that is another story. ***************** "We need to apply 21st-century information technology to the health care field. We need to have our medical records put on the I.T." —GW

                                1 Reply Last reply
                                0
                                • D Dwayner79

                                  To combat this, I wrapped everything into a try catch block. No exceptions thrown. I have changed everything over to the Lock method you suggested. I copied and pasted into the functions and verified no typos. I am at a loss. Thanks for your help. I could post more code if you think it would help. ***************** "We need to apply 21st-century information technology to the health care field. We need to have our medical records put on the I.T." —GW

                                  J Offline
                                  J Offline
                                  jan larsen
                                  wrote on last edited by
                                  #16

                                  There are some things that you can rely on: 1. Only one thread will have access to code inside the lock block. 2. If you still get output like this:

                                  entered lock block
                                  exiting lock block
                                  entered lock block
                                  entered lock block

                                  from code like this:

                                  public void Foo()
                                  {
                                  lock(lockObject)
                                  {
                                  Console.WriteLine("entered lock block");

                                    // Some code
                                  
                                    Console.WriteLine("exiting lock block");
                                  

                                  }
                                  }

                                  Then // Some code must have thrown an exception which was caught and ignored, or logged somewhere else than std output, in the method that invoked Foo(). The only alternative, is that the first WriteLine invocation is placed outside the lock statement. "God doesn't play dice" - Albert Einstein "God not only plays dice, He sometimes throws the dices where they cannot be seen" - Niels Bohr

                                  D 1 Reply Last reply
                                  0
                                  • J jan larsen

                                    There are some things that you can rely on: 1. Only one thread will have access to code inside the lock block. 2. If you still get output like this:

                                    entered lock block
                                    exiting lock block
                                    entered lock block
                                    entered lock block

                                    from code like this:

                                    public void Foo()
                                    {
                                    lock(lockObject)
                                    {
                                    Console.WriteLine("entered lock block");

                                      // Some code
                                    
                                      Console.WriteLine("exiting lock block");
                                    

                                    }
                                    }

                                    Then // Some code must have thrown an exception which was caught and ignored, or logged somewhere else than std output, in the method that invoked Foo(). The only alternative, is that the first WriteLine invocation is placed outside the lock statement. "God doesn't play dice" - Albert Einstein "God not only plays dice, He sometimes throws the dices where they cannot be seen" - Niels Bohr

                                    D Offline
                                    D Offline
                                    Dwayner79
                                    wrote on last edited by
                                    #17

                                    From MSDN: "While a mutual-exclusion lock is held, code executing in the same execution thread can also obtain and release the lock. However, code executing in other threads is blocked from obtaining the lock until the lock is released." This makes it sound like this will only work in multiple threads. A for loop is one thread... is it not. Also, There are two functions being called. Both have to work off the same lock. I tried it with one and it works. I apologize for the confussion. Fromt he original post, I need both functions to work off the same lock. This is what is not working. I can poll the one function (just did 100 times in a row) and it worked fine. when I poll two functions it fails.: for(int i =1; i < 5; i++) { lockedFunction1() lockedFunction2() } What is happening then is this output: Function1 entered Function1 exited Function2 entered Function1 entered Function1 exited Function2 exited (but with an error because value are not right because of mixup. ***************** "We need to apply 21st-century information technology to the health care field. We need to have our medical records put on the I.T." —GW

                                    D J 2 Replies Last reply
                                    0
                                    • D Dwayner79

                                      From MSDN: "While a mutual-exclusion lock is held, code executing in the same execution thread can also obtain and release the lock. However, code executing in other threads is blocked from obtaining the lock until the lock is released." This makes it sound like this will only work in multiple threads. A for loop is one thread... is it not. Also, There are two functions being called. Both have to work off the same lock. I tried it with one and it works. I apologize for the confussion. Fromt he original post, I need both functions to work off the same lock. This is what is not working. I can poll the one function (just did 100 times in a row) and it worked fine. when I poll two functions it fails.: for(int i =1; i < 5; i++) { lockedFunction1() lockedFunction2() } What is happening then is this output: Function1 entered Function1 exited Function2 entered Function1 entered Function1 exited Function2 exited (but with an error because value are not right because of mixup. ***************** "We need to apply 21st-century information technology to the health care field. We need to have our medical records put on the I.T." —GW

                                      D Offline
                                      D Offline
                                      Dwayner79
                                      wrote on last edited by
                                      #18

                                      My point is if there were an exception, we would never see the second function eventually exit. Sorry that was not very clear. ***************** "We need to apply 21st-century information technology to the health care field. We need to have our medical records put on the I.T." —GW

                                      1 Reply Last reply
                                      0
                                      • D Dwayner79

                                        From MSDN: "While a mutual-exclusion lock is held, code executing in the same execution thread can also obtain and release the lock. However, code executing in other threads is blocked from obtaining the lock until the lock is released." This makes it sound like this will only work in multiple threads. A for loop is one thread... is it not. Also, There are two functions being called. Both have to work off the same lock. I tried it with one and it works. I apologize for the confussion. Fromt he original post, I need both functions to work off the same lock. This is what is not working. I can poll the one function (just did 100 times in a row) and it worked fine. when I poll two functions it fails.: for(int i =1; i < 5; i++) { lockedFunction1() lockedFunction2() } What is happening then is this output: Function1 entered Function1 exited Function2 entered Function1 entered Function1 exited Function2 exited (but with an error because value are not right because of mixup. ***************** "We need to apply 21st-century information technology to the health care field. We need to have our medical records put on the I.T." —GW

                                        J Offline
                                        J Offline
                                        jan larsen
                                        wrote on last edited by
                                        #19

                                        It's the second method call that's the problem. No mutex, monitor or lock statement can help you here as they are all concerned about threading. But the output clearly says that you're running multithreaded. The lockedFunction2() invocation will not execute before lockedFunction1() is finished. To get the output you display, lockedFunction1(), lockedFunction2() or both must start another thread that outputs the text. To test for this you could make this change to the output routine:

                                        Console.WriteLine("function 1 entered in thread: " + System.Threading.Thread.CurrentThread.GetHashCode() );

                                        if the hashcode differs in the output, then it's another thread. If it doesn't, then call an Exorcist :-) "God doesn't play dice" - Albert Einstein "God not only plays dice, He sometimes throws the dices where they cannot be seen" - Niels Bohr

                                        D 1 Reply Last reply
                                        0
                                        • J jan larsen

                                          It's the second method call that's the problem. No mutex, monitor or lock statement can help you here as they are all concerned about threading. But the output clearly says that you're running multithreaded. The lockedFunction2() invocation will not execute before lockedFunction1() is finished. To get the output you display, lockedFunction1(), lockedFunction2() or both must start another thread that outputs the text. To test for this you could make this change to the output routine:

                                          Console.WriteLine("function 1 entered in thread: " + System.Threading.Thread.CurrentThread.GetHashCode() );

                                          if the hashcode differs in the output, then it's another thread. If it doesn't, then call an Exorcist :-) "God doesn't play dice" - Albert Einstein "God not only plays dice, He sometimes throws the dices where they cannot be seen" - Niels Bohr

                                          D Offline
                                          D Offline
                                          Dwayner79
                                          wrote on last edited by
                                          #20

                                          Know any good ones ;) entered commandSetBlockParameter in thread: 20 Exited commandSetBlockParameter in thread: 20 entered queryBlockParameter in thread: 20 entered commandSetBlockParameter in thread: 20 Exited commandSetBlockParameter in thread: 20 entered queryBlockParameter in thread: 20 entered commandSetBlockParameter in thread: 20 Exited commandSetBlockParameter in thread: 20 entered queryBlockParameter in thread: 20 Exited queryBlockParameter in thread: 20 Exited queryBlockParameter in thread: 20 That said, Let me add another issue. This is in a timer loop. The timer was ticking before the last passthrough finished. I can disable the timer until the loop completes than reenable it. This may be the only way to fix this. However, The same problem happens elsewhere when I subscribe to an event and I end up writing two values. I will have to fix this and do more testing. Please do not give up on me. You have been a HUGE help. If I respond in a day, will you be here, or should I start a new thread? Thanks so much... Dwayne ***************** "We need to apply 21st-century information technology to the health care field. We need to have our medical records put on the I.T." —GW

                                          D J 2 Replies Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups