ReadThread
using System;
using System.Collections.Generic;
using System.Text;
using System.IO.Ports;
using System.Threading;
using System.Net;
using System.Net.Sockets;
namespace TestTask
{
public delegate void listinvoke(string msg);
interface ReadThread
{
void Read();
void Stop();
}
class TTyReadThread:ReadThread
{
private System.Windows.Forms.ListBox m_listbox=null;
TTyChannel ttychannel = null;
System.IO.Ports.SerialPort m_port=null;
private bool stopped = false;
private WaitHandle readevent=null;
public TTyReadThread(TTyChannel ttychannel, System.Windows.Forms.ListBox listbox, WaitHandle handle)
{
this.ttychannel = ttychannel;
m_listbox = listbox;
stopped = false;
readevent = handle;
}
public void Read()
{
while (!stopped)
{
try
{
string msg = ttychannel.ReadLine();
((AutoResetEvent)readevent).Set();
m_listbox.BeginInvoke(new listinvoke(UpdateList), new object[] { msg });
}
catch (TimeoutException)
{
continue;
}
catch (Exception)
{
continue;
}
}
}
public void Stop()
{
stopped = true;
}
public void UpdateList(string msg)
{
m_listbox.Items.Add(msg);
m_listbox.SelectedIndex = m_listbox.Items.Count - 1;
}
}
class EthReadThread:ReadThread
{
private System.Windows.Forms.ListBox m_listbox = null;
//System.Net.Sockets.Socket m_port = null;
UDPChannel udpchannel = null;
private bool stopped = false;
private WaitHandle readevent = null;
// public EthReadThread(System.Net.Sockets.Socket port, System.Windows.Forms.ListBox listbox, WaitHandle handle)
public EthReadThread(UDPChannel udpchannel, System.Windows.Forms.ListBox listbox, WaitHandle handle)
{
this.udpchannel = udpchannel;
m_listbox = listbox;
stopped = false;
readevent = handle;
}
public void Read()
{
while (!stopped)
{
try
{
string msg=udpchannel.ReadLine();
((AutoResetEvent)readevent).Set();
m_listbox.BeginInvoke(new listinvoke(UpdateList), new object[] { msg });
}
catch (TimeoutException)
{
System.Console.WriteLine("timeout " );
continue;
}
catch (SocketException es)
{
Console.WriteLine("errcode " + es.ErrorCode.ToString());
if (es.SocketErrorCode == SocketError.WouldBlock)
{
System.Console.WriteLine("sock error!\n");
udpchannel.Sock.Blocking=true;
}
continue;
}
catch (Exception e3)
{
System.Console.WriteLine("exception "+e3.Message);
continue;
}
}
}
public void Stop()
{
stopped = true;
}
public void UpdateList(string msg)
{
m_listbox.Items.Add(msg);
m_listbox.SelectedIndex = m_listbox.Items.Count - 1;
}
}
}