2

Please I am using two threads i want one of them to write on Global (shared variable ) and the second thread use the value of the shared variable to start processing it's part of code.

after searching i found the safest way to do that is using Thread Lock but the problem i tried it but it's not working at all really i don't know why is that?

my code as in below :

    namespace WIN_PLC_REV00.SER_TO_PC_CONN
{

    public class SER_Con

    {
        static bool tm = false;
        static Object thisLock = new Object();

        public static  void Ser_Conn_Establish()
        {

            WFControl D = new WFControl(GLP_VAR.SER_CONN.Lib_Fom_Acce.Txt);

            Form1 Fom = (Form1)Application.OpenForms["Form1"];

            SER_GLP_VAR.ipad = IPAddress.Any;
            SER_GLP_VAR.serversocket = new TcpListener(SER_GLP_VAR.ipad, 2000);
            SER_GLP_VAR.clientsocket = default(TcpClient);

            SER_GLP_VAR.serversocket.Start();
            Fom.Invoke(D, new object[] { ">>>>>>_Server Started_<<<<<<<<<" + "\r\n" + SER_GLP_VAR.start.ToString() });

            lock (thisLock)
            {


                tm = true;
            }

            while (true)
            {


                SER_GLP_VAR.clientsocket = SER_GLP_VAR.serversocket.AcceptTcpClient();


                if (Fom.textBox1.InvokeRequired)
                {
                    Fom.Invoke(D, new object[] { "accepted connection from client" + "\r\n" + tm.ToString() });

                }


            }



        }





//////////////////////////////////////
//////// TO get data from client
/// ///////////////////////////////////////////////
        public static void TST()
        {

            int Rec_Msg_Len = 0;
            WFControl Y = new WFControl(GLP_VAR.SER_CONN.Lib_Fom_Acce.Txt);
            Form1 Fom = (Form1)Application.OpenForms["Form1"];


            Fom.Invoke(Y, new object[] { GLP_VAR.SER_CONN.SER_GLP_VAR.str_test.ToString() + "MAHER SECOND PHASE"});

            while (tm )
                {

                    try
                    {

                        NetworkStream networkstream = SER_GLP_VAR.clientsocket.GetStream();
                        byte[] bytesfrom = new byte[10025];
                        if (networkstream.DataAvailable)
                        {
                            networkstream.Read(bytesfrom, 0, (int)SER_GLP_VAR.clientsocket.ReceiveBufferSize);

                            string DataFromClient = System.Text.Encoding.ASCII.GetString(bytesfrom);
                            DataFromClient = DataFromClient.Substring(0, DataFromClient.IndexOf('\0'));
                            if (DataFromClient == "Conn")
                            {
                                Fom.Invoke(Y, new object[] { "connection is up to Data" + ": " + Rec_Msg_Len.ToString() });
                            }
                            else
                            {


                                Rec_Msg_Len = DataFromClient.Length;
                                Fom.Invoke(Y, new object[] { DataFromClient + ": " + Rec_Msg_Len.ToString() });
                            }
                            networkstream.Flush();

                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.ToString());
                    }


                }
        }


}

}

The value of [ tm ] is changing only in thread of method [Ser_Conn_Establish()] but I can't detect it's value inside of thread of method [TST() ]. this is first step for me because should after that i need to take the buffer of data to a global character array but i am still straggling in this point.

I am sure i am doing something wrong.

Thanks, Moelsayed

moha
  • 51
  • 5
  • What does "not working at all" mean? That doesn't help anyone understand your issue. A C# `lock` statement is a wrapper around the `Monitor` class. If you lock on an object, you will block when you try to enter the lock-block if any other thread is executing a lock-block based on the same object. I see only one `lock` statement, so unless all your threads are trying to run `Ser_Conn_Establish`, no blocking will occur. Also note that 4-byte reads and writes are atomic in C#, so you may not need a lock at all. If you want to do read/increment/etc. operations on ints, look at `Interlock` – Flydog57 Nov 29 '18 at 21:09
  • i meant that the first method[ Ser_Conn_Establish ] changing the value of (tm ) but in the next method [TST] when I tried to use (tm) value to allow getting data from client I found (tm) value still equal False , and honestly I need a simple example for using Lock statement to write on shared variable because I need to understand well the luck function. – moha Nov 29 '18 at 22:55
  • It's not a function, it's a C# statement that translates into try/finally code around the use of .NET's `System.Threading.Monitor`. If you search for "lock" or "System.Threading.Monitor" (or both) along with "C#" and "example", you should find something – Flydog57 Nov 29 '18 at 23:14
  • I got your point first of all i am very new in threading and c# and i need your help to do the below: - I have two different threads created from two different methods. - one of these threads should set value of a global (shared ) variable and another thread when he found the value of the shared variable equal 1 then start do something else. this what i want to do and i am so sorry for my wrong terminology. – moha Nov 30 '18 at 17:02
  • Read this post, and the links that are referenced in the post. You can use `lock` - it's always the safest bet. But, realize that in order for the lock to do something, there needs to be at least two `lock` statements that can be executed in at least two threads (they may be the same piece of code being executed from multiple threads). If you are setting and testing a flag, set the flag within one `lock` with an assignment, and then read the flag (with an assignment) in another `lock` statement. Then, test the variable you just assigned outside the `lock`. That will always be save AFAIK. – Flydog57 Nov 30 '18 at 17:24
  • Forgot the post to read: https://stackoverflow.com/questions/19382705/c-sharp-volatile-keyword-usage-vs-lock – Flydog57 Nov 30 '18 at 17:24

0 Answers0