gpt4 book ai didi

multithreading - Thread.Sleep() 和 Thread.SpinWait() 有什么区别

转载 作者:可可西里 更新时间:2023-11-01 02:40:54 27 4
gpt4 key购买 nike

我有一个 WinForm 应用程序,它使用 BackGroundWorker 创建 TCP 客户端并将一些数据发送到远程服务器。当套接字完成时关闭连接,BGW 从 DoWork Sub 退出。

在 RunWorkerCompleted Sub 中,我必须等待来自远程服务器的数据包,因此我一直在运行一个 TCP 服务器,该服务器填充 Friend String 类型变量并使用 bool 类型变量(标志)指示接收到整个数据包。

所以我必须等待那个标志变为True来处理必须在String类型变量中的数据;但我不想挂断 GUI,所以我看到存在一个名为 SpinWait 的方法。

那么,这段代码可以工作吗?

如果 flag 在 5 分钟后没有变为 true,有什么办法可以退出循环?

Private Sub BGW1_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BGW1.RunWorkerCompleted
While Not AckReady
System.Threading.Thread.SpinWait(500)
End While

'Here process the received data from TCP server

TmrReport.Start()

End Sub

另一件事是,多少次迭代代表 500mS?

最佳答案

根据文档:

Thread.SpinWait Method

The SpinWait method is useful for implementing locks. Classes in the .NET Framework, such as Monitor and ReaderWriterLock, use this method internally. SpinWait essentially puts the processor into a very tight loop, with the loop count specified by the iterations parameter. The duration of the wait therefore depends on the speed of the processor.

Contrast this with the Sleep method. A thread that calls Sleep yields the rest of its current slice of processor time, even if the specified interval is zero. Specifying a non-zero interval for Sleep removes the thread from consideration by the thread scheduler until the time interval has elapsed.

因此,Sleep 基本上释放处理器,以便它可以被其他东西使用,而 SpinWait 运行一个循环,使处理器保持忙碌(并锁定到其他线程) .

关于multithreading - Thread.Sleep() 和 Thread.SpinWait() 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29851910/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com