zl程序教程

您现在的位置是:首页 >  后端

当前栏目

.NET中STAThread的使用详解

Net 使用 详解
2023-06-13 09:14:52 时间

在WindowForm应用程序中主要的线程,是采用一种称为「Single-ThreadedApartment(STA)」的线程模型。这个STA线程模型,在线程内加入了讯息帮浦等等机制,减少开发人员撰写窗口程序的工作量。
 

而在开发类别库的时候,如果要使用类似的STA线程模型,可以使用下列的程序代码提供的类别来完成。

复制代码代码如下:

namespaceCLK.Threading
{
   publicclassSTAThread
   {
       //Enum
       privateenumThreadState
       {
           Started,
           Stopping,
           Stopped,
       }

 
       //Fields
       privatereadonlyobject_syncRoot=newobject();

       privatereadonlyBlockingQueue<Action>_actionQueue=null;

       privateThread_thread=null;

       privateManualResetEvent_threadEvent=null;

       privateThreadState_threadState=ThreadState.Stopped;     

 
       //Constructor
       publicSTAThread()
       {
           //ActionQueue
           _actionQueue=newBlockingQueue<Action>();

           //ThreadEvent
           _threadEvent=newManualResetEvent(true);

           //ThreadState
           _threadState=ThreadState.Stopped;     
       }

 
       //Methods
       publicvoidStart()
       {          
           //Sync
           lock(_syncRoot)
           {
               //ThreadState
               if(_threadState!=ThreadState.Stopped)thrownewInvalidOperationException();
               _threadState=ThreadState.Started;
           }

           //Thread
           _thread=newThread(this.Operate);
           _thread.Name=string.Format("Class:{0},Id:{1}","STAThread",_thread.ManagedThreadId);
           _thread.IsBackground=false;
           _thread.Start();
       }

       publicvoidStop()
       {
           //Sync
           lock(_syncRoot)
           {
               //ThreadState
               if(_threadState!=ThreadState.Started)thrownewInvalidOperationException();
               _threadState=ThreadState.Stopping;

               //ActionQueue
               _actionQueue.Release();
           }

           //Wait
           _threadEvent.WaitOne();
       }

 
       publicvoidPost(SendOrPostCallbackcallback,objectstate)
       {
           #regionContracts

           if(callback==null)thrownewArgumentNullException();

           #endregion

           //Action
           Actionaction=delegate()
           {
               try
               {
                   callback(state);
               }
               catch(Exceptionex)
               {
                   Debug.Fail(string.Format("Delegate:{0},State:{1},Message:{2}",callback.GetType(),"Exception",ex.Message));
               }
           };

           //Sync
           lock(_syncRoot)
           {
               //ThreadState
               if(_threadState!=ThreadState.Started)thrownewInvalidOperationException();

               //ActionQueue
               _actionQueue.Enqueue(action);
           }                     
       }

       publicvoidSend(SendOrPostCallbackcallback,objectstate)
       {
           #regionContracts

           if(callback==null)thrownewArgumentNullException();

           #endregion

           //Action
           ManualResetEventactionEvent=newManualResetEvent(false);
           Actionaction=delegate()
           {
               try
               {
                   callback(state);
               }
               catch(Exceptionex)
               {
                   Debug.Fail(string.Format("Delegate:{0},State:{1},Message:{2}",callback.GetType(),"Exception",ex.Message));
               }
               finally
               {
                   actionEvent.Set();
               }
           };

           //Sync
           lock(_syncRoot)
           {
               //ThreadState
               if(_threadState!=ThreadState.Started)thrownewInvalidOperationException();

               //ActionQueue
               if(Thread.CurrentThread!=_thread)
               {
                   _actionQueue.Enqueue(action);
               }
           }

           //Execute
           if(Thread.CurrentThread==_thread)
           {
               action();
           }

           //Wait
           actionEvent.WaitOne();
       }

 
       privatevoidOperate()
       {
           try
           {
               //Begin
               _threadEvent.Reset();

               //Operate
               while(true)
               {
                   //Action
                   Actionaction=_actionQueue.Dequeue();

                   //Execute
                   if(action!=null)
                   {
                       action();
                   }

                   //ThreadState
                   if(action==null)
                   {
                       lock(_syncRoot)
                       {
                           if(_threadState==ThreadState.Stopping)
                           {
                               return;
                           }
                       }
                   }
               }
           }
           finally
           {
               //End
               lock(_syncRoot)
               {
                   _threadState=ThreadState.Stopped;
               }
               _threadEvent.Set();
           }
       }
   }
}

复制代码代码如下:

namespaceCLK.Threading
{
   publicclassBlockingQueue<T>
   {
       //Fields      
       privatereadonlyobject_syncRoot=newobject();

       privatereadonlyWaitHandle[]_waitHandles=null;

       privatereadonlyQueue<T>_itemQueue=null;

       privatereadonlySemaphore_itemQueueSemaphore=null;

       privatereadonlyManualResetEvent_itemQueueReleaseEvent=null;

 
       //Constructors
       publicBlockingQueue()
       {
           //Default
           _itemQueue=newQueue<T>();
           _itemQueueSemaphore=newSemaphore(0,int.MaxValue);
           _itemQueueReleaseEvent=newManualResetEvent(false);
           _waitHandles=newWaitHandle[]{_itemQueueSemaphore,_itemQueueReleaseEvent};
       }

 
       //Methods
       publicvoidEnqueue(Titem)
       {
           lock(_syncRoot)
           {
               _itemQueue.Enqueue(item);
               _itemQueueSemaphore.Release();
           }
       }

       publicTDequeue()
       {
           WaitHandle.WaitAny(_waitHandles);
           lock(_syncRoot)
           {
               if(_itemQueue.Count>0)
               {
                   return_itemQueue.Dequeue();
               }
           }
           returndefault(T);
       }

       publicvoidRelease()
       {
           lock(_syncRoot)
           {
               _itemQueueReleaseEvent.Set();
           }
       }

       publicvoidReset()
       {
           lock(_syncRoot)
           {
               _itemQueue.Clear();
               _itemQueueSemaphore.Close();
               _itemQueueReleaseEvent.Reset();
           }
       }
   }
}