How to stop IrDAListener?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

1.Following is my sample code

IrDAListener listener;
private void button3_Click(object sender, System.EventArgs e)
{
try
{

listener = new IrDAListener("CPMonitor");
listener.Start();


}
catch
{
listener.Stop();
}
}

private void button4_Click(object sender, System.EventArgs e)
{
listener.Stop();
}

if press button3 first,then press button4,repeat these steps.Everything is ok.
if press button3 twice,the second time will throw a exception.It's no use to
call
listener.stop().At this situation,pressing button3 will always throw
exception.Why?

2.I have a worker thread to monitor IrDA.
private void serverRoutine()
{

try
{

listener = new IrDAListener("CPMonitor");
listener.Start();


}
catch
{
listener.Stop();
return;
}
}

while (isRunning)
{
if (listener.Pending())
{
IrDAClient client = listener.AcceptIrDAClient();
NetworkStream ns = (NetworkStream) client.GetStream();

while (isRunning)
{
try
{
ns.Read(buf,0,len);
......
}
catch (SocketException sex)
{ break;
}
catch (IOException ex)
{
break;
}
catch
{
}
finally
{
}
}
}
else
Thread.Sleep(50);
}


I set isRunning = false,call listener.Stop(),which can stop thread.But when
I create the thread again,listener.Start() will always cause Exception. How
can avoid this?


Thanks in advance.

wyghf
 
The problem you are creating is that if you press the buttons out of
sequence you assign a new listener to your listener variable effectively
losing control of the original copy (until the garbage controller tries to
free it up). What you should consider instead is create the listener only
once e.g. at startup and then simply use stop and start when you want to
stop and restart listening. The other issue is that before calling stop or
start you can check the status with the Active property - only call Start if
Active is false, and Stop if active is true.

Peter
 
Thanks.You're right.

Peter Foot said:
The problem you are creating is that if you press the buttons out of
sequence you assign a new listener to your listener variable effectively
losing control of the original copy (until the garbage controller tries to
free it up). What you should consider instead is create the listener only
once e.g. at startup and then simply use stop and start when you want to
stop and restart listening. The other issue is that before calling stop or
start you can check the status with the Active property - only call Start if
Active is false, and Stop if active is true.

Peter
 
Back
Top