.NET中STAThread的使用详解

 更新时间:2021年9月22日 10:15  点击:1441

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

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

复制代码 代码如下:

namespace CLK.Threading
{
    public class STAThread
    {
        // Enum
        private enum ThreadState
        {
            Started,
            Stopping,
            Stopped,
        }

 
        // Fields
        private readonly object _syncRoot = new object();

        private readonly BlockingQueue<Action> _actionQueue = null;

        private Thread _thread = null;

        private ManualResetEvent _threadEvent = null;

        private ThreadState _threadState = ThreadState.Stopped;     

 
        // Constructor
        public STAThread()
        {
            // ActionQueue
            _actionQueue = new BlockingQueue<Action>();

            // ThreadEvent
            _threadEvent = new ManualResetEvent(true);

            // ThreadState
            _threadState = ThreadState.Stopped;     
        }

 
        // Methods
        public void Start()
        {          
            // Sync
            lock (_syncRoot)
            {
                // ThreadState
                if (_threadState != ThreadState.Stopped) throw new InvalidOperationException();
                _threadState = ThreadState.Started;
            }

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

        public void Stop()
        {
            // Sync
            lock (_syncRoot)
            {
                // ThreadState
                if (_threadState != ThreadState.Started) throw new InvalidOperationException();
                _threadState = ThreadState.Stopping;

                // ActionQueue
                _actionQueue.Release();
            }

            // Wait
            _threadEvent.WaitOne();
        }

 
        public void Post(SendOrPostCallback callback, object state)
        {
            #region Contracts

            if (callback == null) throw new ArgumentNullException();

            #endregion

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

            // Sync
            lock (_syncRoot)
            {
                // ThreadState
                if (_threadState != ThreadState.Started) throw new InvalidOperationException();

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

        public void Send(SendOrPostCallback callback, object state)
        {
            #region Contracts

            if (callback == null) throw new ArgumentNullException();

            #endregion

            // Action
            ManualResetEvent actionEvent = new ManualResetEvent(false);
            Action action = delegate()
            {
                try
                {
                    callback(state);
                }
                catch (Exception ex)
                {
                    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) throw new InvalidOperationException();

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

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

            // Wait
            actionEvent.WaitOne();
        }

 
        private void Operate()
        {
            try
            {
                // Begin
                _threadEvent.Reset();

                // Operate
                while (true)
                {
                    // Action
                    Action action = _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();
            }
        }
    }
}

复制代码 代码如下:

namespace CLK.Threading
{
    public class BlockingQueue<T>
    {
        // Fields      
        private readonly object _syncRoot = new object();

        private readonly WaitHandle[] _waitHandles = null;

        private readonly Queue<T> _itemQueue = null;

        private readonly Semaphore _itemQueueSemaphore = null;

        private readonly ManualResetEvent _itemQueueReleaseEvent = null;

 
        // Constructors
        public BlockingQueue()
        {
            // Default
            _itemQueue = new Queue<T>();
            _itemQueueSemaphore = new Semaphore(0, int.MaxValue);
            _itemQueueReleaseEvent = new ManualResetEvent(false);
            _waitHandles = new WaitHandle[] { _itemQueueSemaphore, _itemQueueReleaseEvent };
        }

 
        // Methods
        public void Enqueue(T item)
        {
            lock (_syncRoot)
            {
                _itemQueue.Enqueue(item);
                _itemQueueSemaphore.Release();
            }
        }

        public T Dequeue()
        {
            WaitHandle.WaitAny(_waitHandles);
            lock (_syncRoot)
            {
                if (_itemQueue.Count > 0)
                {
                    return _itemQueue.Dequeue();
                }
            }
            return default(T);
        }

        public void Release()
        {
            lock (_syncRoot)
            {
                _itemQueueReleaseEvent.Set();
            }
        }

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

[!--infotagslink--]

相关文章

  • ASP.NET购物车实现过程详解

    这篇文章主要为大家详细介绍了ASP.NET购物车的实现过程,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-09-22
  • .NET Core下使用Kafka的方法步骤

    这篇文章主要介绍了.NET Core下使用Kafka的方法步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-09-22
  • 在ASP.NET 2.0中操作数据之七十二:调试存储过程

    在开发过程中,使用Visual Studio的断点调试功能可以很方便帮我们调试发现程序存在的错误,同样Visual Studio也支持对SQL Server里面的存储过程进行调试,下面就让我们看看具体的调试方法。...2021-09-22
  • Win10 IIS 安装.net 4.5的方法

    这篇文章主要介绍了Win10 IIS 安装及.net 4.5及Win10安装IIS并配置ASP.NET 4.0的方法,本文给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下...2021-09-22
  • 详解.NET Core 3.0 里新的JSON API

    这篇文章主要介绍了详解.NET Core 3.0 里新的JSON API,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-09-22
  • .net数据库操作框架SqlSugar的简单入门

    这篇文章主要介绍了.net数据库操作框架SqlSugar的简单入门,帮助大家更好的理解和学习使用.net技术,感兴趣的朋友可以了解下...2021-09-22
  • ASP.NET Core根据环境变量支持多个 appsettings.json配置文件

    这篇文章主要介绍了ASP.NET Core根据环境变量支持多个 appsettings.json配置文件,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-09-22
  • 记一次EFCore类型转换错误及解决方案

    这篇文章主要介绍了记一次EFCore类型转换错误及解决方案,帮助大家更好的理解和学习使用asp.net core,感兴趣的朋友可以了解下...2021-09-22
  • .NET C#利用ZXing生成、识别二维码/条形码

    ZXing是一个开放源码的,用Java实现的多种格式的1D/2D条码图像处理库,它包含了联系到其他语言的端口。这篇文章主要给大家介绍了.NET C#利用ZXing生成、识别二维码/条形码的方法,文中给出了详细的示例代码,有需要的朋友们可以参考借鉴。...2020-06-25
  • 详解ASP.NET Core 中基于工厂的中间件激活的实现方法

    这篇文章主要介绍了ASP.NET Core 中基于工厂的中间件激活的实现方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-09-22
  • C#使用Ado.Net更新和添加数据到Excel表格的方法

    这篇文章主要介绍了C#使用Ado.Net更新和添加数据到Excel表格的方法,较为详细的分析了OLEDB的原理与使用技巧,可实现较为方便的操作Excel数据,需要的朋友可以参考下...2020-06-25
  • asp.net通过消息队列处理高并发请求(以抢小米手机为例)

    这篇文章主要介绍了asp.net通过消息队列处理高并发请求(以抢小米手机为例),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-09-22
  • ASP.NET 2.0中的数据操作:使用两个DropDownList过滤的主/从报表

    在前面的指南中我们研究了如何显示一个简单的主/从报表, 该报表使用DropDownList和GridView控件, DropDownList填充类别,GridView显示选定类别的产品. 这类报表用于显示具有...2016-05-19
  • ASP.NET单选按钮控件RadioButton常用属性和方法介绍

    RadioButton又称单选按钮,其在工具箱中的图标为 ,单选按钮通常成组出现,用于提供两个或多个互斥选项,即在一组单选钮中只能选择一个...2021-09-22
  • 详解.NET Core 使用HttpClient SSL请求出错的解决办法

    这篇文章主要介绍了.NET Core 使用HttpClient SSL请求出错的解决办法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2021-09-22
  • Python调用.NET库的方法步骤

    这篇文章主要介绍了Python调用.NET库的方法步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-05-09
  • ASP.NET中iframe框架点击左边页面链接 右边显示链接页面内容

    这篇文章主要介绍了ASP.NET中iframe框架点击左边页面链接,右边显示链接页面内容的实现代码,感兴趣的小伙伴们可以参考一下...2021-09-22
  • 创建一个完整的ASP.NET Web API项目

    ASP.NET Web API具有与ASP.NET MVC类似的编程方式,ASP.NET Web API不仅仅具有一个完全独立的消息处理管道,而且这个管道比为ASP.NET MVC设计的管道更为复杂,功能也更为强大。下面创建一个简单的Web API项目,需要的朋友可以参考下...2021-09-22
  • ASP.NET连接MySql数据库的2个方法及示例

    这篇文章主要介绍了ASP.NET连接MySql数据库的2个方法及示例,使用的是MySQL官方组件和ODBC.NET,需要的朋友可以参考下...2021-09-22
  • Asp.Net使用Bulk实现批量插入数据

    这篇文章主要介绍了Asp.Net使用Bulk实现批量插入数据的方法,对于进行asp.net数据库程序设计非常有借鉴价值,需要的朋友可以参考下...2021-09-22