我对Thread有点问题。我执行函数Receive,超时设置为600,但它在此结束
if ((thr.ThreadState != ThreadState.Running)
&& (thr.ThreadState != ThreadState.WaitSleepJoin))
{
ThreadState st = thr.ThreadState;
lg.WriteString("EXIT BY THREAD END");
lg.WriteString("LAST: "+st.ToString());
break;
}
只有当线程结束并且我已经收到所有数据时,函数才会结束,但是当我打开文件errores.txt时,我看到ThreadState值是Running或WaitSleepJoin。
知道该函数为什么会中止?
以下更多代码 - >
bool exit = false;
void WaitAndRead() {
if (buffer == null)
buffer = new List<byte>();
buffer.Clear();
try
{
while (sock_client.Available < 1 && !exit)
Thread.Sleep(10);
while (sock_client.Available > 0 && !exit)
{
byte[] b = new byte[sock_client.Available];
sock_client.Receive(b, 0, b.Length, SocketFlags.None);
buffer.AddRange(b);
Thread.Sleep(25);
}
}
catch (Exception ex)
{
Log lg = new Log("C:\\TPV\\errores.txt");
lg.WriteException(ex, true);
}
public int Receive(int timeout,out List<byte> result)
{
result = new List<byte>();
try
{
if (!Connected)
return NOT_CONNECTED;
bool ok = true;
ThreadStart str = delegate
{
try { WaitAndRead(); }
catch (Exception ex)
{
Log lg = new Log("C:\\TPV\\errores.txt");
lg.WriteException(ex, true); ok = false; }
};
exit = false;
Thread thr = new Thread(str);
thr.Start();
int x = 0;
int max = 10 * timeout;
while (x < max)
{
Log lg = new Log("C:\\TPV\\errores.txt");
if ((thr.ThreadState != ThreadState.Running)
&& (thr.ThreadState != ThreadState.WaitSleepJoin))
{
ThreadState st = thr.ThreadState;
lg.WriteString("EXIT BY THREAD END");
lg.WriteString("LAST: "+st.ToString());
break;
}
x++;
Thread.Sleep(10);
}
exit = true;
if (x >= max)
return Timeout;
result = new List<byte>(buffer.ToArray());
return ok?OK:NOT_CONNECTED;
}
catch(Exception ex)
{
Log lg = new Log("C:\\TPV\\errores.txt");
lg.WriteException(ex, true);
return NOT_CONNECTED;
}
}
答案 0 :(得分:4)
在此代码评估时,ThreadState
属性的值可能会发生变化:
if ((thr.ThreadState != ThreadState.Running) && (thr.ThreadState != ThreadState.WaitSleepJoin))
{
ThreadState st = thr.ThreadState;
lg.WriteString("EXIT BY THREAD END");
lg.WriteString("LAST: "+st.ToString());
break;
}
考虑以下情况:
thr.ThreadState
是WaitSleepJoin
if
语句的第一部分评估为true
thr.ThreadState
的第二部分之前,Running
更改为if
if
语句的第二部分评估为true
true
,因此输入了if
块您可以尝试重写代码,如下所示,这样您只需检查一次ThreadState
属性的值:
var state = thr.ThreadState;
if (state != ThreadState.Running && state != ThreadState.WaitSleepJoin)
{
lg.WriteString("EXIT BY THREAD END");
lg.WriteString("LAST: "+ state.ToString());
break;
}
答案 1 :(得分:2)
我注意到Microsoft的ThreadState属性的一些注释:
http://msdn.microsoft.com/en-us/library/system.threading.thread.threadstate.aspx
特别指出:
线程状态仅在调试方案中有用。你的代码 永远不应该使用线程状态来同步活动 线程。
您是否要考虑使用Monitor或Mutex对象?