C # Creating a secure stack (stack) storage structure _c# Tutorial

Source: Internet
Author: User
Tags thread class

In C #, the structure used for storage is more, such as: Datatable,dataset,list,dictionary,stack structure, the storage of various structure of the way there are differences, efficiency must have advantages and disadvantages. Now we're going to introduce a LIFO data structure.

When it comes to storage structures, we use more of them in our projects. For a task storage structure, stacks and queues are similar structures that are used in different ways. C # medium stack (stack) is the memory space allocated during compilation, so you must have a clear definition of the stack size in your code; The heap is the memory space that is dynamically allocated during the program run, and you can determine the size of the heap memory to allocate according to the running of the program.

In C #, stacks usually hold the steps of our code execution. reference types in C # are stored on the stack, and each thread (threads) maintains its own proprietary thread stack as the program runs. When a method is invoked, the main thread begins in the metadata of the owning assembly, finds the invoked method, and then compiles it by JIT and puts the result (typically the local CPU instruction) on top of the stack. The CPU takes the instruction from the stack through the bus, and the driver executes it.

The above data structure of the stack is a simple introduction, now look at the C # implementation stack structure of the bottom method:

  <summary>///Initializes a new instance of the <see cref= "T:System.Collections.Generic.Stack ' 1"/> class, which is empty and has the default initial capacity.
  </summary> [__dynamicallyinvokable] public Stack (); <summary>///Initializes a new instance of the <see cref= "T:System.Collections.Generic.Stack ' 1"/> class, the instance is empty,
  Has the specified initial capacity or the default initial capacity (the larger one). </summary>///<param name= "Capacity" ><see cref= "T:System.Collections.Generic.Stack ' 1"/> The number of initial elements that can be included. </param><exception cref= "T:System.ArgumentOutOfRangeException" ><paramref name= "Capacity"/> is
  Less than zero.</exception> [__dynamicallyinvokable] public Stack (int capacity); <summary>///Initializes a new instance of the <see cref= "T:System.Collections.Generic.Stack ' 1"/> class,
  The instance contains elements that are copied from the specified collection and has sufficient capacity to accommodate the copied elements. </summary>///<param name= "Collection" > The collection from which elements are copied. </param><exception cref= "T:System.ArgumentNullException" ><paramref name= "collection"/> is null. </exception> [__dynamicallyinvokable] PUblic Stack (ienumerable<t> collection);
 

The above is an introduction to some of the methods of stack, which take into account the security of the thread while manipulating the data store.

As the basic unit of the Operating system execution program, the process has the resources of the application, the process contains the thread, the process's resources are shared by the thread, and the thread does not own the resource. Threads are divided into foreground threads and background threads, creating new lines through the thread class Cheng think of foreground threads. When all foreground threads are closed, all background threads are also terminated directly, and no exceptions are thrown.

Next look at the ReaderWriterLockSlim class:

  <summary>///represents the lock state used to manage resource access, which enables multi-threaded reads or exclusive write access. </summary> [__dynamicallyinvokable] [HostProtection (SecurityAction.LinkDemand, externalthreading = True, Synchronization = True)] [HostProtection (SecurityAction.LinkDemand, Mayleakonabort = True)] public class Readerwriterlo  ckslim:idisposable {///<summary>///initializes <see cref= "T:System.Threading.ReaderWriterLockSlim" with default property values/>
  The new instance of the class.
  </summary> [__dynamicallyinvokable] public readerwriterlockslim ();
  <summary>///Initializes a new instance of the <see cref= "T:System.Threading.ReaderWriterLockSlim"/> class when a locking recursive policy is specified. </summary>///<param Name= is one of the "Recursionpolicy" > Enumeration values used to specify a locking recursive policy.
  </param> [__dynamicallyinvokable] public ReaderWriterLockSlim (Lockrecursionpolicy recursionpolicy);
  <summary>///attempted to enter read mode lock state. </summary>///<exception cref= "t:system.threading.lockrecursionexception" ><see cref= "P: System.Threading.ReaderWritErlockslim.recursionpolicy "/> attribute is <see cref=" F:System.Threading.LockRecursionPolicy.NoRecursion "/> And the current thread has entered the read mode. -or-the current thread may not acquire a read lock when it already contains a write lock. -or-the recursive number will exceed the capacity of the counter. This limitation is very large for applications that should never encounter it. </exception><exception cref= "T:System.ObjectDisposedException" ><see cref= "T: System.Threading.ReaderWriterLockSlim "/> object has been disposed.
  </exception> [__dynamicallyinvokable] public void Enterreadlock ();
  <summary>///attempt to enter the lock in read mode, you can select a timeout.
  </summary>//////<returns>///True if the calling thread has entered read mode; </returns>///<param name= "Timeout" > Wait interval, or 1 milliseconds, to indicate an indefinite wait. </param><exception cref= "t:system.threading.lockrecursionexception" ><see cref= "P: System.Threading.ReaderWriterLockSlim.RecursionPolicy "/> property is <see cref=" F: System.Threading.LockRecursionPolicy.NoRecursion "/> and the current thread have entered the lock. -or-the recursive number will exceed the capacity of the counter. Limit the application should never encounter it too large. </exception><exception cref= "T:System.ArgumentOutOfRangeException" > Value <pAramref name= "Timeout"/> is negative, but it is not equal to 1 milliseconds, which is the only allowable value that is negative. -or-value <paramref name= "Timeout"/> is greater than <see cref= "F:System.Int32.MaxValue"/> milliseconds. </exception><exception cref= "T:System.ObjectDisposedException" ><see cref= "T: System.Threading.ReaderWriterLockSlim "/> object has been disposed.
  </exception> [__dynamicallyinvokable] public bool Tryenterreadlock (TimeSpan timeout);
  <summary>///attempt to enter the lock in read mode, you can select an integer timeout.
  </summary>//////<returns>///True if the calling thread has entered read mode; </returns>///<param name= "millisecondstimeout" > The number of milliseconds to wait, or 1 <see cref= "F: System.Threading.Timeout.Infinite "/>", which means waiting indefinitely. </param><exception cref= "t:system.threading.lockrecursionexception" ><see cref= "P: System.Threading.ReaderWriterLockSlim.RecursionPolicy "/> property is <see cref=" F: System.Threading.LockRecursionPolicy.NoRecursion "/> and the current thread have entered the lock. -or-the recursive number will exceed the capacity of the counter. Limit the application should never encounter it too large. </exception><exception cref= "T:System.ArgumentOutOfRangeException "> Value <paramref name=" millisecondstimeout "/> is negative, but it is not equal to <see cref=" F: System.Threading.Timeout.Infinite "/> (-1), which is the only allowable value that is negative. </exception><exception cref= "T:System.ObjectDisposedException" ><see cref= "T: System.Threading.ReaderWriterLockSlim "/> object has been disposed.
  </exception> [__dynamicallyinvokable] public bool Tryenterreadlock (int millisecondstimeout);
  <summary>///attempted to enter the lock in write mode. </summary>///<exception cref= "t:system.threading.lockrecursionexception" ><see cref= "P: System.Threading.ReaderWriterLockSlim.RecursionPolicy "/> property is <see cref=" F: System.Threading.LockRecursionPolicy.NoRecursion "/> and the current thread have entered the lock in any mode. -or-the current thread has entered the read mode, so attempting to enter the lock state write mode creates the possibility of a deadlock. -or-the recursive number will exceed the capacity of the counter. Limit the application should never encounter it too large. </exception><exception cref= "T:System.ObjectDisposedException" ><see cref= "T: System.Threading.ReaderWriterLockSlim "/> object has been disposed. </exception> [__dynamicallyinvokable] Public void Enterwritelock ();
  <summary>///attempt to enter the lock in write mode, you can select a timeout.
  </summary>//////<returns>///True if the calling thread has entered write mode; </returns>///<param name= "Timeout" > Wait interval, or 1 milliseconds, to indicate an indefinite wait. </param><exception cref= "t:system.threading.lockrecursionexception" ><see cref= "P: System.Threading.ReaderWriterLockSlim.RecursionPolicy "/> property is <see cref=" F: System.Threading.LockRecursionPolicy.NoRecursion "/> and the current thread have entered the lock. -or-the current thread originally entered the lock in read mode, so attempting to enter write mode creates the possibility of causing a deadlock. -or-the recursive number will exceed the capacity of the counter. Limit the application should never encounter it too large. </exception><exception cref= "T:System.ArgumentOutOfRangeException" > Value <paramref name= "Timeout"/> is a negative number, but it is not equal to 1 milliseconds, which is the only allowable value that is negative. -or-value <paramref name= "Timeout"/> is greater than <see cref= "F:System.Int32.MaxValue"/> milliseconds. </exception><exception cref= "T:System.ObjectDisposedException" ><see cref= "T: System.Threading.ReaderWriterLockSlim "/> object has been disposed. </exception> [__dynamicallyinvokable] Public bool Tryenterwritelock (TimeSpan timeout);
  <summary>///attempt to enter the lock in write mode, you can select a timeout.
  </summary>//////<returns>///True if the calling thread has entered write mode; </returns>///<param name= "millisecondstimeout" > The number of milliseconds to wait, or 1 <see cref= "F: System.Threading.Timeout.Infinite "/>", which means waiting indefinitely. </param><exception cref= "t:system.threading.lockrecursionexception" ><see cref= "P: System.Threading.ReaderWriterLockSlim.RecursionPolicy "/> property is <see cref=" F: System.Threading.LockRecursionPolicy.NoRecursion "/> and the current thread have entered the lock. -or-the current thread originally entered the lock in read mode, so attempting to enter write mode creates the possibility of causing a deadlock. -or-the recursive number will exceed the capacity of the counter. Limit the application should never encounter it too large. </exception><exception cref= "T:System.ArgumentOutOfRangeException" > Value <paramref name= " Millisecondstimeout "/> is negative, but it is not equal to <see cref=" F:System.Threading.Timeout.Infinite "/> (-1), which is the only allowable value is negative. </exception><exception cref= "T:System.ObjectDisposedException" ><see cref= "T: System.Threading.ReaderWriterLockSlim"The/> object has been disposed.
  </exception> [__dynamicallyinvokable] public bool Tryenterwritelock (int millisecondstimeout);
  <summary>///attempted to enter the upgradeable mode lock state. </summary>///<exception cref= "t:system.threading.lockrecursionexception" ><see cref= "P: System.Threading.ReaderWriterLockSlim.RecursionPolicy "/> property is <see cref=" F: System.Threading.LockRecursionPolicy.NoRecursion "/> and the current thread have entered the lock in any mode. -or-the current thread has entered the read mode, so attempting to enter upgradeable mode will have the possibility of deadlock. -or-the recursive number will exceed the capacity of the counter. Limit the application should never encounter it too large. </exception><exception cref= "T:System.ObjectDisposedException" ><see cref= "T: System.Threading.ReaderWriterLockSlim "/> object has been disposed.
  </exception> [__dynamicallyinvokable] public void Enterupgradeablereadlock ();
  <summary>///try to enter the upgradeable mode lock state, and you can select a timeout period.
  </summary>//////<returns>///True if the calling thread has entered upgradeable mode; </returns>///<param name= "Timeout" > Wait interval, or 1 milliseconds, to indicate an indefinite wait. </param><exception cref= "T:system.thrEading. Lockrecursionexception "><see cref=" P:system.threading.readerwriterlockslim.recursionpolicy "/> Property is < The cref= "F:System.Threading.LockRecursionPolicy.NoRecursion"/> and the current thread have entered the lock. -or-the current thread originally entered the lock in read mode, so attempting to enter upgradeable mode creates the possibility of causing a deadlock. -or-the recursive number will exceed the capacity of the counter. Limit the application should never encounter it too large. </exception><exception cref= "T:System.ArgumentOutOfRangeException" > Value <paramref name= "Timeout"/> is a negative number, but it is not equal to 1 milliseconds, which is the only allowable value that is negative. -or-value <paramref name= "Timeout"/> is greater than <see cref= "F:System.Int32.MaxValue"/> milliseconds. </exception><exception cref= "T:System.ObjectDisposedException" ><see cref= "T: System.Threading.ReaderWriterLockSlim "/> object has been disposed.
  </exception> [__dynamicallyinvokable] public bool Tryenterupgradeablereadlock (TimeSpan timeout);
  <summary>///try to enter the upgradeable mode lock state, and you can select a timeout period.
  </summary>//////<returns>///True if the calling thread has entered upgradeable mode; </returns>///<param name= "millisecondstimeout" > Waiting milliseconds, or 1 (<seE cref= "F:System.Threading.Timeout.Infinite"/>), which means waiting indefinitely. </param><exception cref= "t:system.threading.lockrecursionexception" ><see cref= "P: System.Threading.ReaderWriterLockSlim.RecursionPolicy "/> property is <see cref=" F: System.Threading.LockRecursionPolicy.NoRecursion "/> and the current thread have entered the lock. -or-the current thread originally entered the lock in read mode, so attempting to enter upgradeable mode creates the possibility of causing a deadlock. -or-the recursive number will exceed the capacity of the counter. Limit the application should never encounter it too large. </exception><exception cref= "T:System.ArgumentOutOfRangeException" > Value <paramref name= " Millisecondstimeout "/> is negative, but it is not equal to <see cref=" F:System.Threading.Timeout.Infinite "/> (-1), which is the only allowable value is negative. </exception><exception cref= "T:System.ObjectDisposedException" ><see cref= "T: System.Threading.ReaderWriterLockSlim "/> object has been disposed.
  </exception> [__dynamicallyinvokable] public bool Tryenterupgradeablereadlock (int millisecondstimeout);
  <summary>///reduces the recursive count of read mode and exits read mode when the generated count is 0 (0). </summary>///<exception cref= "T:system.threading.synchronizationlockeXception "> in read mode, the current thread is going into the lock.
  </exception> [__dynamicallyinvokable] public void Exitreadlock ();
  <summary>///reduces the recursive count of write mode and exits write mode when the generated count is 0 (0). </summary>///<exception cref= "T:System.Threading.SynchronizationLockException" > The current thread is locked into write mode.
  </exception> [__dynamicallyinvokable] public void Exitwritelock ();
  <summary>///reduces the recursive count of upgradeable modes and exits upgradeable mode when the generated count is 0 (0). </summary>///<exception cref= "t:system.threading.synchronizationlockexception" > Current thread is locked into upgradeable mode.
  </exception> [__dynamicallyinvokable] public void Exitupgradeablereadlock ();
  <summary>///frees all resources used by the current instance of the <see cref= "T:System.Threading.ReaderWriterLockSlim"/> class. </summary>///<exception cref= "t:system.threading.synchronizationlockexception" ><see cref= "P: System.Threading.ReaderWriterLockSlim.WaitingReadCount "/> is greater than 0. -or-<see cref= "P:system.threading.readerwriterlockslim.waitingupgradecount"/> is greater than 0. -or-<see cref= "P:system.threading.readerwriterlockslim.waitingwritecount"/> is greater than 0.
  </exception><filterpriority>2</filterpriority> [__dynamicallyinvokable] public void Dispose ();
  <summary>///Gets a value that indicates whether the current thread has entered the lock state in read mode.
  </summary>//////<returns>///True if the current thread has entered read mode; </returns>///<filterpriority>2</filterpriority> [__dynamicallyinvokable] public bool Isreadl
  Ockheld {[__dynamicallyinvokable] get;}
  <summary>///Gets a value that indicates whether the current thread has entered a locked state in upgradeable mode.
  </summary>//////<returns>///True if the current thread has entered upgradeable mode; </returns>///<filterpriority>2</filterpriority> [__dynamicallyinvokable] public bool Isupgra
  Deablereadlockheld {[__dynamicallyinvokable] get;}
  <summary>///Gets a value that indicates whether the current thread has entered a lock in write mode. </summary>//////<returns>///True if the current thread has entered write mode;to False. </returns>///<filterpriority>2</filterpriority> [__dynamicallyinvokable] public bool Iswrite
  Lockheld {[__dynamicallyinvokable] get;}
  <summary>///Gets a value that indicates the recursive policy for the current <see cref= "T:System.Threading.ReaderWriterLockSlim"/> object.
  One of the </summary>//////<returns>///enumeration values that specifies the locking recursive policy. </returns> [__dynamicallyinvokable] public lockrecursionpolicy recursionpolicy {[__dynamicallyinvokable] ge T
  ///<summary>///Gets the total number of unique threads that have entered the lock in read mode.
  </summary>//////<returns>///The number of unique threads that have entered the lock state for read mode.
  </returns> [__dynamicallyinvokable] public int Currentreadcount {[__dynamicallyinvokable] get;}
  <summary>///Gets the number of times the current thread has entered the lock in read mode to indicate recursion. </summary>//////<returns>///is 0 (0) If the current thread is not in read mode, 1 if the thread has entered read mode but is not entered recursively, or if the thread has entered recursively
  Lock mode n-1 times, then N. </returns>///<filterpriority>2</filterpriority> [__dynamicallyinvokable] public int Recursivereadcount {[__dynamicallyinvokable] get;}
  <summary>///Gets the number of times the current thread has entered the locked state of upgradeable mode, which is used to indicate recursion. </summary>//////<returns>///If the current thread does not enter upgradeable mode, 0, or 1 if the thread has entered upgradeable mode but is not entered recursively, or if the thread has entered recursively to
  The upgrade mode is n-1 times, then N. </returns>///<filterpriority>2</filterpriority> [__dynamicallyinvokable] public int Recursiv
  Eupgradecount {[__dynamicallyinvokable] get;}
  <summary>///Gets the number of times the current thread has entered the lock in write mode to indicate recursion. </summary>//////<returns>///is 0 if the current thread does not enter write mode, or 1 if the thread has entered write mode but is not entered recursively, or if the thread has entered the write mode recursively
  Type n-1 times, then N. </returns>///<filterpriority>2</filterpriority> [__dynamicallyinvokable] public int Recursiv
  Ewritecount {[__dynamicallyinvokable] get;}
  <summary>///Gets the total number of threads waiting to enter the lock in read mode.
  </summary>//////<returns>///The total number of threads waiting to enter read mode. </returns>///<filterpriority>2</filterpriority> [__dynamicallyinvokable] public int Waitingreadcount {[__ Dynamicallyinvokable] get;
  ///<summary>///Gets the total number of threads waiting to enter upgradeable mode lock state.
  </summary>//////<returns>///The total number of threads waiting to enter upgradeable mode. </returns>///<filterpriority>2</filterpriority> [__dynamicallyinvokable] public int Waitingu
  Pgradecount {[__dynamicallyinvokable] get;}
  <summary>///Gets the total number of threads waiting to enter the lock in write mode.
  </summary>//////<returns>///The total number of threads waiting to enter write mode. </returns>///<filterpriority>2</filterpriority> [__dynamicallyinvokable] public int Waitingw
 Ritecount {[__dynamicallyinvokable] get;} }

The above is a brief description of the knowledge about stack and threads, now describes thread-safe stack:

 <summary>///represents an object's LIFO security set (stack structure)///</summary>///<typeparam name= "T" ></typeparam> public class Tstack<t>: Ienumerable<t&gt, ICollection {///<summary>///internal Stack///</

    summary> private readonly stack<t> _mstack; <summary>///lock Access Stack, which is used to manage the lock state of resource access, to enable multi-threaded reads or exclusive write access.

    )///</summary> private readonly ReaderWriterLockSlim _lockstack = new ReaderWriterLockSlim (); <summary>///only for SyncRoot properties///</summary> Private ReadOnly Object _objsyncroot = new Object ()

    ;
    Variables///<summary>///Initializes a new instance <see cref= "Tstack{t}"/> class.
    </summary> public tstack () {_mstack = new stack<t> ();
    ///<summary>///Initializes a new instance <see cref= "Tstack{t}"/> class. </summary>///<param name= "col" >///start collection///</param> public tstack (IenuMerable<t> col) {_mstack = new stack<t> (col); }//Init///<summary>///Get enumerator///</summary> public ienumerator<t> Getenumerato

      R () {stack<t> localstack = null; Initializes the enumerator _lockstack.performusingreadlock (() => {///Create a m_tlist copy localstack = new STACK&L T
      T> (_mstack);

      });
    Gets the enumerator (T item in Localstack) yield return item;
      ///<summary>///Get enumerator///</summary> IEnumerator Ienumerable.getenumerator () {

      Stack<t> localstack = null; Initializes the enumerator _lockstack.performusingreadlock (() => {//Create a copy of m_tlist localstack = new stack& Lt
      T> (_mstack);

      });
    Gets the enumerator (T item in Localstack) yield return item; ///<summary>///copied to an array///</summary>///<param name= "Array" ></PARAM&GT <param name= "index" ></param> public void CopyTo (array array, int index) {_lockstack.perform Usingreadlock (() => _mstack.toarray ().
    CopyTo (array, index)); Number of items in the///<summary>///stack///</summary> public int Count {get {RE
      Turn _lockstack.performusingreadlock (() => _mstack.count); ///<summary>///is always true///</summary> public bool IsSynchronized {get {ret Urn true; }///<summary>///sync root///</summary> public object SyncRoot {get {return _ Objsyncroot; }///<summary>///Purge collection///</summary> public void Clear () {_lockstack.perf
    Ormusingwritelock (() => _mstack.clear ()); }//Clear///<summary>///If the item is on the stack, true///</summary>///<param name= "Item" >& Lt;/param>///<returns></returns>
    public bool Contains (T Item) {return _lockstack.performusingreadlock (() => _mstack.contains (item)); //contains///<summary>///returns the top item in the stack without removing it from the stack///</summary>///<returns></re
    Turns> public T Peek () {return _lockstack.performusingreadlock (() => _mstack.peek ()); }//Peek///<summary>///Delete and return top item in stack///</summary>///<RETURNS></RETURNS&G
    T
    Public T POPs () {return _lockstack.performusingwritelock () => _mstack.pop ()); //Pop///<summary>///inserts a project into the stack///</summary>///<param name= "Item" ></par
    am> public void Push (T item) {_lockstack.performusingwritelock (() => _mstack.push (item));
    //Push///<summary>///convert stacks to arrays///</summary>///<returns></returns> Public t[] ToArray () {return _lockstack.performusIngreadlock (() => _mstack.toarray ());
    }//ToArray///<summary>///Sets the capacity to the actual number of elements in the stack///</summary> public void trimexcess ()
    {_lockstack.performusingwritelock (() => _mstack.trimexcess ());

 }
  }

The above operation method inherits the Ienumerable<t> ICollection two interfaces. Interested, can have a detailed understanding of the Ienumerable<t>, ICollection two interfaces.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.