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

标签 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 时间片可以(也应该)放弃给其他线程,对吗? (如果我错了请纠正我)

非常感谢。

最佳答案

是的,它是 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 状态中花费大量时间。

关于c# - 当发出同步 I/O 调用时,当前线程 (C#) 的 ThreadState 是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29027922/

相关文章:

c# - 如何返回正确的检查 float.Parse(String)?

c# - 如何通过 lambda 从列表中获取一种类型的 child ?

C# 模拟 Windows 中的默认拖放功能(拖动过程中的透明图像)

c# - 如何使用 await/async 等待资源

c# - 将 ComboBox 的 SelectedValue 分配给 viewmodel wpf 的字符串属性

android - Android 中的 EditText 值

python - 制作一个 "Any Key"可中断的 Python 定时器

c++ - 混合 C 和 C++ 的线程同步

流处理异步测试

javascript - async.waterfall 和 async.series 有什么区别