Click here to Skip to main content
15,914,014 members
Home / Discussions / C#
   

C#

 
QuestionScanning QR code Pin
Member 123142768-Feb-16 7:13
Member 123142768-Feb-16 7:13 
AnswerRe: Scanning QR code Pin
OriginalGriff8-Feb-16 8:09
mveOriginalGriff8-Feb-16 8:09 
AnswerRe: Scanning QR code Pin
Sascha Lefèvre8-Feb-16 8:15
professionalSascha Lefèvre8-Feb-16 8:15 
QuestionC# iTexSharp How to put PDF page number during creation PDF File Pin
Zefir18-Feb-16 2:38
Zefir18-Feb-16 2:38 
AnswerRe: C# iTexSharp How to put PDF page number during creation PDF File Pin
Richard MacCutchan8-Feb-16 3:17
mveRichard MacCutchan8-Feb-16 3:17 
GeneralRe: C# iTexSharp How to put PDF page number during creation PDF File Pin
Zefir18-Feb-16 3:27
Zefir18-Feb-16 3:27 
GeneralRe: C# iTexSharp How to put PDF page number during creation PDF File Pin
Richard MacCutchan8-Feb-16 3:50
mveRichard MacCutchan8-Feb-16 3:50 
QuestionIs this serial port class and how I use it thred safe? Pin
Member 120616007-Feb-16 21:07
Member 120616007-Feb-16 21:07 
I modified and updated my previous question by clarifying it more and adding some details, I would appreciate help on it as I am stuck with it.

I have a serial port class which looks something like below.
Please don't pay much attention at the WriteAll and ReadAll function contents- I don't think it matters much as far as thread safety is concerned. Please see below for more details.

C#
public static class HASPClass
      {


          static readonly object m_locker = new object();
          private static SerialPort m_port;
          private static string m_portName;
          private static bool m_isOpen = false;

          private static int m_baudRate;
          private static Parity m_parity;
          private static int m_dataBits;
          private static StopBits m_stopBits;
          private static bool m_xonxoff;
          private static bool m_dtr;
          private static bool m_rts;

          // ................................

          // Some constants
          public static uint m_WR_ERROR = 0;
          public static uint m_IO_ERROR = 0;
          public static uint m_IO_ERROR1 = 0;
          public static uint m_IO_ERROR2 = 0;
          public static uint m_IO_ERROR3 = 0;


          // Open port.
          public static void OpenPort(string portName,
                                      int baudRate,
                                      Parity parity,
                                      int dataBits,
                                      StopBits stopBits,
                                      bool dtr,
                                      bool rts,
                                      bool xonxoff = false)
          {

           lock(m_locker){
              if(m_isOpen) return;
              // Create new Serial Port object
              m_port = new SerialPort(portName, baudRate, parity, dataBits, stopBits);

              // .........................................
              // Set class member variables.

              m_portName = portName;
              m_baudRate = baudRate;
              m_parity = parity;
              m_dataBits = dataBits;
              m_stopBits = stopBits;
              m_xonxoff = xonxoff;
              m_dtr = dtr;
              m_rts = rts;

              // ............................................
              // Initialize some port object properties

              // XOnXOff - parameter
              if (xonxoff)
                  m_port.Handshake = Handshake.XOnXOff;

              // Set DTR/RTS
              m_port.DtrEnable = dtr;
              m_port.RtsEnable = rts;

              // Set
              m_port.ReadTimeout = 500;
              m_port.WriteTimeout = 500;

              // ..............................................
              // Some final steps.

              // Open the port for communications
              m_port.Open();

              // If we get this far, mark port as opened.
              m_isOpen = true;
           }
          }

          public static void Close()
          {
                lock(m_locker){
                    if(m_isOpen) m_port.Close();
                }
          }

          /// <summary>
          /// Just makes sure to read the specified number of bytes from the serial port.
          /// Typical reads may return fewer bytes then told to read. This method is used
          /// to avoid this problem.
          /// Based on a similar function from Jon Skeet: http://jonskeet.uk/csharp/readbinary.html
          /// </summary>
          /// <param name="data"> [OUT] Data read should be stored here</param>
          /// <param name="length"> [IN] How much data to read exactly </param>
          /// <param name="count"> [IN] Some kind of retry count parameter.</param>
          private static void ReadAll(byte[] data, uint length, int retryCount)
          {

              // Check data length parameter.
              if (length > data.Length)
              {
                  throw new Exception("Wrong data length in ReadAll");
              }

              int offset = 0;
              int i = 0;
              int remaining = checked((int)length); // NOTE: Will throw OverflowException if length > Int32.MaxValue due to checked keyword.

              // Start reading.
              while (remaining > 0)
              {
                  // Just a retry count check
                  if (i >= retryCount)
                  {
                      throw new Exception("Exceeded retry count parameter during reading in ReadAll");
                  }

                  // Read Certain amount of bytes
                  int read = m_port.Read(data, offset, remaining);

                  // Was there error?
                  if (read <= 0)
                  {
                      throw new EndOfStreamException(String.Format("ReadAll(OldHaspCommunication) - End of data reached with {0} bytes left to read", remaining));
                  }

                  // Advance offset, and decrease remaining count.
                  remaining -= read;
                  offset += read;

                  i++;

              }


          }

          /// <summary>
          /// Write specified number of bytes to the serial port
          /// </summary>
          /// <param name="data"> [IN] Buffer from which to write data</param>
          /// <param name="length"> [IN] How many bytes to write</param>
          private static void WriteAll(byte[] data, uint length)
          {
              // TODO: Maybe we should add a retry count as in C++

              int len = checked((int)length); // NOTE: Will throw OverflowException if length > Int32.MaxValue due to checked keyword.

              // We can't write more data to serial port than available in the array.
              if (len > data.Length)
              {
                  throw new Exception("Wrong data length in WriteAll");
              }

              // Do the write.
              m_port.Write(data, 0, len);
          }

          public void Query(..)
          {
            lock(m_locker){
             // Protocol to talk to HASP
             WriteAll(..);
             ReadAll(..);
             WriteAll(..);
             ReadAll(..);
             }
          }

  }


As you can see ReadAlland WriteAllcalls are private. Query is public and it calls ReadAll and WriteAll methods hence I put lock only inside Query.

Now imagine I have different class which wants to use Query method (after it has done OpenPort):

C#
class Tester
  {

   static readonly object m_otherlockA= new object();
   public static void function1()
   {
     lock(m_otherlockA)
     {
        HASPCLass.Query(..);
        HASPCLass.Query(..);
      }
   }

   public static void start()
   {
      HASPCLass.OpenPort(...)
   }

   public static void End()
   {
      HASPCLass.Close(...)
   }

   public static void function2()
   {
     lock(m_otherlockA)
     {
        HASPCLass.Query(..);
        HASPCLass.Query(..);
      }
   }
  }


My question is: Is the way I use HASPClass from class Tester thread safe? In other words HASP class will be used via Tester class only - is it thread safe?

I would really appreciate some help as I am stuck on it.

modified 8-Feb-16 6:16am.

AnswerRe: Is this serial port class and how I use it thred safe? Pin
Daniel Pfeffer7-Feb-16 21:29
professionalDaniel Pfeffer7-Feb-16 21:29 
GeneralRe: Is this serial port class and how I use it thred safe? Pin
Member 120616007-Feb-16 21:41
Member 120616007-Feb-16 21:41 
GeneralRe: Is this serial port class and how I use it thred safe? Pin
Daniel Pfeffer7-Feb-16 22:10
professionalDaniel Pfeffer7-Feb-16 22:10 
GeneralRe: Is this serial port class and how I use it thred safe? Pin
Member 120616007-Feb-16 22:13
Member 120616007-Feb-16 22:13 
GeneralRe: Is this serial port class and how I use it thred safe? Pin
Member 120616008-Feb-16 0:11
Member 120616008-Feb-16 0:11 
GeneralRe: Is this serial port class and how I use it thred safe? Pin
Daniel Pfeffer8-Feb-16 2:07
professionalDaniel Pfeffer8-Feb-16 2:07 
GeneralRe: Is this serial port class and how I use it thred safe? Pin
Member 120616008-Feb-16 2:10
Member 120616008-Feb-16 2:10 
AnswerRe: Is this serial port class and how I use it thred safe? Pin
Jochen Arndt7-Feb-16 21:47
professionalJochen Arndt7-Feb-16 21:47 
GeneralRe: Is this serial port class and how I use it thred safe? Pin
Member 120616007-Feb-16 21:52
Member 120616007-Feb-16 21:52 
GeneralRe: Is this serial port class and how I use it thred safe? Pin
Jochen Arndt7-Feb-16 22:09
professionalJochen Arndt7-Feb-16 22:09 
GeneralRe: Is this serial port class and how I use it thred safe? Pin
Member 120616007-Feb-16 22:13
Member 120616007-Feb-16 22:13 
GeneralRe: Is this serial port class and how I use it thred safe? Pin
Jochen Arndt7-Feb-16 22:36
professionalJochen Arndt7-Feb-16 22:36 
GeneralRe: Is this serial port class and how I use it thred safe? Pin
Member 120616007-Feb-16 23:26
Member 120616007-Feb-16 23:26 
GeneralRe: Is this serial port class and how I use it thred safe? Pin
Jochen Arndt7-Feb-16 23:35
professionalJochen Arndt7-Feb-16 23:35 
GeneralRe: Is this serial port class and how I use it thred safe? Pin
Member 120616007-Feb-16 23:59
Member 120616007-Feb-16 23:59 
GeneralRe: Is this serial port class and how I use it thred safe? Pin
Jochen Arndt8-Feb-16 0:19
professionalJochen Arndt8-Feb-16 0:19 
GeneralRe: Is this serial port class and how I use it thred safe? Pin
Member 120616008-Feb-16 0:20
Member 120616008-Feb-16 0:20 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.