当发出同步I / O调用时,当前线程(C#)的ThreadState是什么?

时间:2015-03-13 08:39:31

标签: c# multithreading asynchronous

以下是我的代码:

static int Main(string[] args)
{
    Thread current_thread = Thread.CurrentThread;

    new Thread(() => { var i = 0; while (++i > 0) { Thread.Sleep(100); Console.WriteLine("Thread: " + current_thread.ManagedThreadId + ", State: " + current_thread.ThreadState + ", I: " + i); } }).Start();

    while(true)
    {
        Console.WriteLine("Thread: " + Thread.CurrentThread.ManagedThreadId + ", State: " + Thread.CurrentThread.ThreadState);

        // creating a http request...
        // ...
        requst.GetResponseStream(); // this is the synchronous call 
    }
}

输出显示当前线程(主线程)的状态始终为ThreadState.Running。所以,为什么,为什么不是ThreadState.WaitSleepJoin

GetResponseStream()是同步的。在等待远程响应时,cpu时间片可以(并且应该)放弃到其他线程,对吧? (如果我错了,请纠正我)

非常感谢你。

1 个答案:

答案 0 :(得分:3)

是的,它是WaitSleepJoin。您的示例代码显然是不完整和错误的(例如,您没有启动新主题),因此不容易说出为什么您没有看到正确的值。您是否始终为GetResponseStream创建新请求?

此代码显示了您的预期:

Thread current_thread = Thread.CurrentThread;

new Thread(() => 
{ 
  var i = 0; while (++i > 0) 
  { 
    if ((current_thread.ThreadState & System.Threading.ThreadState.WaitSleepJoin) > 0) 
      Console.WriteLine("Thread: " + current_thread.ManagedThreadId 
       + ", State: " + current_thread.ThreadState + ", I: " + i); 
  } 
}
).Start();

while(true)
{
    Console.WriteLine("Thread: " + Thread.CurrentThread.ManagedThreadId 
      + ", State: " + Thread.CurrentThread.ThreadState);

    var request = HttpWebRequest.CreateHttp("http://www.google.com/");

    using (var response = request.GetResponse())
    {
        using (var stream = response.GetResponseStream())
        {
            stream.Read(new byte[2048], 0, 2048);
        }
    } 
}

棘手的部分是它没有花费大量时间在WaitSleepJoin州。