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

标签 multithreading sockets tcp

我有一个 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/

相关文章:

c++ - 错误 : ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function

c++ - 仅在套接字 C++ 中返回内容

python - 我的服务器(Python套接字)有什么问题?

c# - 如果未检测到换行符,则服务器的套接字阻塞,但未检测到客户端的套接字

javascript - PortQry与ElectronJS Desktop App的集成

python-3.x - 如何重用套接字地址python?

multithreading - 如何安排运行的非阻塞函数

c# - 如何正确关闭在线程中打开的 TcpClient

java - 如何确定高延迟网络请求的最佳线程数?

linux - 我需要一个 TCP 选项 (ioctl) 来立即发送数据