Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between Thread.Sleep() and Thread.SpinWait()

I have a WinForm application that uses a BackGroundWorker to create a TCP Client and send some data to a remote server. When the socket finish close the connection and the BGW exits from the DoWork Sub.

In the RunWorkerCompleted Sub I must to wait a packet from the remote server, so I have always running a TCP server that fills a Friend String type variable and indicates that the whole packet is received using a Boolean type variable(flag).

So I must to wait that flag to becomes True to process the data that must be in the String type variable; but I don't want to hang up the GUI so I see that exist a method called SpinWait.

So, Can this code works?

There's any way to get out if the loop if the flag doesn't to true 5 minutes later?

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 

Another things is, How many iterations represent 500mS?

like image 354
E_Blue Avatar asked Sep 11 '25 21:09

E_Blue


1 Answers

Per the documentation:

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.

So, Sleep basically releases the processor so it can be used by something else, whereas SpinWait runs a loop that keeps the processor busy (and locked to other threads).

like image 118
C. Ridley Avatar answered Sep 14 '25 23:09

C. Ridley