110,538
社区成员
发帖
与我相关
我的任务
分享
public void Poll()
{
foreach (var station in stations)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadPollCallback), COMMStates[station.Id]);
}
if (WaitHandle.WaitAll(COMMStates.Select(p => p.Value.Completed).ToArray(), millsecondsTimeout, false))
{
}
else
{
Console.WriteLine("timeout");
foreach (var cs in COMMStates)
{
if (cs.Value != null)
{
cs.Value.Abort();
}
}
}
}
public void ThreadPollCallback(object state)
{
var cs = state as COMMState;
if (cs == null) return;
var station = cs.Station;
using (TcpClient tc = new TcpClient(station.IP, 3100)) //在这里报错
{
try
{
Console.WriteLine("comm thread start");
if (cs.Aborted)
{
Console.WriteLine("comm thread abort");
try
{
tc.GetStream().Close();
}
catch
{
}
try { tc.Close(); }
catch { }
}
else
{
COMMIpMaster master = COMMIpMaster.CreateIp(tc);
var length = master.ReadWaveLength();//这里就是一个write,一个read
if (length % 24 != 0)
{
throw new Exception("长度不正确");
}
ushort[] res = master.ReadWaveData((ushort)length);//这里就是一个write,一个read
lock (lockObj)
{
Data[station.Id] = new List<ushort>(res);
stationErrNum[station.Id] = 0;
Exceptions[station.Id] = null;
}
}
}
catch (Exception e)
{
Console.WriteLine("comm thread error");
lock (lockObj)
{
Exceptions[station.Id] = e;
stationErrNum[station.Id]++;
if (stationErrNum[station.Id] > 3)
{
Data[station.Id] = new List<ushort>(12); ;
}
}
}
finally
{
cs.Completed.Set();
}
}
}
public class COMMState
{
public Station Station;
public volatile Thread Thread;
public readonly ManualResetEvent Completed = new ManualResetEvent(false);
public volatile Exception Exception;
public volatile bool Aborted;
public void Abort()
{
if (!Aborted)
{
Aborted = true;
try { Thread.Abort(); }
catch { }
}
}
}