Recently, some C #2.0Code... Discover unsafe implementations of various threads
No concurrentcollection classes in 2.0
As a last resort, I wrote one myself,
Originally intended to use the traditional lock implementation, but considering that the operation is very lightweight... Eventually still uses the lock free
Use interlocked to replace common lock keywords.
Public Sealed Class Safedqueue <t>
{
# Region Private Fields
Private Int Istaked = 0 ;
Private Queue <t> queue =New Queue <t> ();
Private Int Maxcount = 1000 * 1000 ;
# Endregion
Public Void Enqueue (T)
{
Try
{
While (Interlocked. Exchange ( Ref Istaked,1 )! = 0 )
{
}
This . Queue. enqueue (t );
}
Finally
{
Thread. volatilewrite ( Ref Istaked, 0 );
}
}
Public T dequeue ()
{
Try
{
While (Interlocked. Exchange ( Ref Istaked, 1 )! = 0 )
{
}
T = This . Queue. dequeue ();
Return T;
}
Finally
{
Thread. volatilewrite ( Ref Istaked, 0 );
}
}
Public Bool Tryenqueue (T)
{
Try
{
For ( Int I = 0 ; I <maxcount; I ++)
{
If (Interlocked. Exchange ( Ref Istaked, 1 ) = 0 )
{
This . Queue. enqueue (t );
Return True ;
}
}
Return False ;
}
Finally
{
Thread. volatilewrite ( Ref Istaked, 0 );
}
}
Public Bool Trydequeue ( Out T)
{
Try
{
For ( Int I = 0 ; I <maxcount; I ++)
{
If (Interlocked. Exchange ( Ref Istaked, 1 ) = 0 )
{
T = This . Queue. dequeue ();
Return True ;
}
}
T = Default (T );
Return False ;
}
Finally
{
Thread. volatilewrite ( Ref Istaked, 0 );
}
}
}
Methods Starting with try have a limit on the number of attempts. If the limit is exceeded, the system exits and returns false.