ApartmentState

本文详细介绍了System.Threading.Thread中的STA(单线程单元)和MTA(多线程单元)的区别。STA线程拥有独立资源,适用于如WinForm等场景;而MTA线程共享资源,例如线程池。默认情况下线程为MTA,且线程的ApartmentState属性只能设置一次。

ApartmentState用来指定 System.Threading.Thread 的单元状态。是一个枚举类型变量。有三个枚举成员。

分别是STA、MTA、Unknown。

STA:    System.Threading.Thread 将创建并进入一个单线程单元

MTA:   System.Threading.Thread 将创建并进入一个多线程单元

Unknown尚未设置 System.Threading.Thread.ApartmentState 属性

一个Thread实例之后可以使用SetAppartmentState方法设置线程的单元状态,

每个线程只可以设置一次,若再次设置会抛异常。

在不设置线程的AppartmentState时,默认值是MTA。


STA和MTA的主要区别应该是他们对资源的占用情况:
STA线程都有自己独立的资源,别的线程访问不到,比如winform
MTA可以共用一个资源,ThreadPool就是一个很好的MTA例子

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; using System.Net.Sockets; using Modbus.Device; using Modbus.Data; using Modbus.Message; using System.Threading; using System.Windows.Forms; namespace ModbusP { //轮询Modbus服务器的寄存器 class ModbusTcpClient { static private TcpClient client; private IModbusMaster master; static public bool cFlag = false; static public ushort[] m_registers; public ModbusTcpClient(string ipAddress, int port, int timeout) { client = new TcpClient(ipAddress, port); client.ReceiveTimeout = timeout; client.SendTimeout = timeout; master = ModbusIpMaster.CreateIp(client); } public async Task<ushort[]> ReadHoldingRegisters(ushort startAddress, ushort numberOfPoints) //表示一个可以返回值的异步操作 { //slave:从站的地址 //startAddress:这是要读取的第一个保持寄存器的地址。 //numberOfPoints:这是要读取的保持寄存器的数量。 return await master.ReadHoldingRegistersAsync(0, startAddress, numberOfPoints);//异步读取Modbus从站的保持寄存器 } public void PollHoldingRegisters(ushort startAddress, ushort numberOfPoints, int interval) { Thread th_0 = new Thread(() => { while (cFlag) { try { m_registers = ReadHoldingRegisters(startAddress, numberOfPoints).Result; //MessageBox.Show($"Polled at {DateTime.Now}: {string.Join(", ", registers)}", "Polling Result", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (SocketException ex) { MessageBox.Show($"Socket error: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } catch (Exception ex) { MessageBox.Show($"Error: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } Thread.Sleep(interval); } }) { IsBackground = true, }; th_0.SetApartmentState(ApartmentState.STA); th_0.Start(); } static public void Close() { client.Close(); } } }
03-08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值