我对线程有一点问题。我执行超时设置为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;
    }
  }

最佳答案

此代码正在评估时,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.ThreadStateWaitSleepJoin
  • 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;
    }
    

    关于c# - 线程正在退出,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9083848/

    10-10 11:28