ReadThread

ydlydl413 2008-12-04 02:16:08
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;
}
}
}
...全文
110 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
net5i 2008-12-05
  • 打赏
  • 举报
回复
晕,搂主有何疑问?
king19840811 2008-12-05
  • 打赏
  • 举报
回复
关注帮顶?

110,536

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧