Kahhoe
asked on
What actually "label.visble = true" did?
The code below is extracted from one of my project, it will hang when there a client is connected. When I make some changes in the showConnected() function, the program work well. I would like to know why!!
//The code below is at the main page
private void btOpenPort_Click(object sender, System.EventArgs e)
{
Connector = new TcpServer(Int32.Parse(tbPo rt.Text), this);
Thread runSrv = new Thread(new ThreadStart(Connector.Open Port));
runSrv.Start();
}
public void showConnected()
{
//lbConnected is a label
lbConnected.visible = true;
}
//These the code run is another thread
public TcpServer(int port, Server theBoss)
{
PortNo = port;
boss = theBoss;
}
public void OpenPort()
{
Listener = new TcpListener(PortNo);;
Listener.Start();
Socket ConnectionSocket;
NetworkStream socketStream;
BinaryReader reader;
BinaryWriter writer;
while(!programClosed)
{
ConnectionSocket = Listener.AcceptSocket();
boss.showConnected();
socketStream = new NetworkStream(ConnectionSo cket);
writer = new BinaryWriter(socketStream) ;
reader = new BinaryReader(socketStream) ;
ClientReader = reader;
}
}
When I initially set the visible of lbConnected.visible = false and lbConnected.Text = "" and modified the showConnected function as below, the program work well, why?
public void showConnected()
{
lbConnected.Text = "Client Connected !!";
}
//The code below is at the main page
private void btOpenPort_Click(object sender, System.EventArgs e)
{
Connector = new TcpServer(Int32.Parse(tbPo
Thread runSrv = new Thread(new ThreadStart(Connector.Open
runSrv.Start();
}
public void showConnected()
{
//lbConnected is a label
lbConnected.visible = true;
}
//These the code run is another thread
public TcpServer(int port, Server theBoss)
{
PortNo = port;
boss = theBoss;
}
public void OpenPort()
{
Listener = new TcpListener(PortNo);;
Listener.Start();
Socket ConnectionSocket;
NetworkStream socketStream;
BinaryReader reader;
BinaryWriter writer;
while(!programClosed)
{
ConnectionSocket = Listener.AcceptSocket();
boss.showConnected();
socketStream = new NetworkStream(ConnectionSo
writer = new BinaryWriter(socketStream)
reader = new BinaryReader(socketStream)
ClientReader = reader;
}
}
When I initially set the visible of lbConnected.visible = false and lbConnected.Text = "" and modified the showConnected function as below, the program work well, why?
public void showConnected()
{
lbConnected.Text = "Client Connected !!";
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
As i said you should use Delegates with Invoke/BeginInvoke if you access the UI Thread from other Threads. That means every Control you wan't to modify/change/add should be Invoked. Without that it can run, but it can throw Exceptions. So its safer to use it.
ASKER