Windows apps
Collapse the table of content
Expand the table of content
Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

SpinWait::Reset Method ()

.NET Framework (current version)
 

Resets the spin counter.

Namespace:   System.Threading
Assembly:  mscorlib (in mscorlib.dll)

public:
void Reset()

This makes SpinOnce and NextSpinWillYield behave as though no calls to SpinOnce had been issued on this instance. If a SpinWait instance is reused many times, it may be useful to reset it to avoid yielding too soon.

The following is an example of using SpinWait in a simple lock-free stack implementation. (This is just an example. If an efficient, thread-safe stack is needed, consider using ConcurrentStack.)

// C#

public class LockFreeStack<T>

{

private volatile Node m_head;

private class Node { public Node Next; public T Value; }

public void Push(T item)

{

var spin = new SpinWait();

Node node = new Node { Value = item }, head;

while (true)

{

head = m_head;

node.Next = head;

if (Interlocked.CompareExchange(ref m_head, node, head) == head) break;

spin.SpinOnce();

}

}

public bool TryPop(out T result)

{

result = default(T);

var spin = new SpinWait();

Node head;

while (true)

{

head = m_head;

if (head == null) return false;

if (Interlocked.CompareExchange(ref m_head, head.Next, head) == head)

{

result = head.Value;

return true;

}

spin.SpinOnce();

}

}

}

' Visual Basic

Public Class LockFreeStack(Of T)

Private m_head As Node

Private Class Node

Public [Next] As Node

Public Value As T

End Class

Public Sub Push(ByVal item As T)

Dim spin As New SpinWait()

Dim head As Node, node As New Node With {.Value = item}

While True

Thread.MemoryBarrier()

head = m_head

node.Next = head

If Interlocked.CompareExchange(m_head, node, head) Is head Then Exit While

spin.SpinOnce()

End While

End Sub

Public Function TryPop(ByRef result As T) As Boolean

result = CType(Nothing, T)

Dim spin As New SpinWait()

Dim head As Node

While True

Thread.MemoryBarrier()

head = m_head

If head Is Nothing Then Return False

If Interlocked.CompareExchange(m_head, head.Next, head) Is head Then

result = head.Value

Return True

End If

spin.SpinOnce()

End While

End Function

End Class

Universal Windows Platform
Available since 8
.NET Framework
Available since 4.0
Portable Class Library
Supported in: portable .NET platforms
Windows Phone Silverlight
Available since 8.0
Windows Phone
Available since 8.1
Return to top
Show:
© 2017 Microsoft