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