首页 > 解决方案 > 使用 C# 连接生物识别设备?

问题描述

我正在尝试在 Web 应用程序中连接生物识别设备。我在 windows 应用程序中工作正常,但在 web 中它会抛出错误。

Windows-form.cs:

int nPort = Convert.ToInt32(textPort.Text);
                        int nPassword = Convert.ToInt32(textPassword.Text);
                        string strIP = ipAddressControl1.IPAddress.ToString();
                        bRet = axFP_CLOCK.SetIPAddress(ref strIP, nPort, nPassword);
                        if(!bRet)
                        {
                            return;
                        }

表单设计器:

((System.ComponentModel.ISupportInitialize)(this.axFP_CLOCK)).BeginInit();
       this.axFP_CLOCK.Enabled = true;
            this.axFP_CLOCK.Location = new System.Drawing.Point(476, 382);
            this.axFP_CLOCK.Name = "axFP_CLOCK";
            this.axFP_CLOCK.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axFP_CLOCK.OcxState")));
            this.axFP_CLOCK.Size = new System.Drawing.Size(100, 50);
            this.axFP_CLOCK.TabIndex = 11;
            this.axFP_CLOCK.Visible = false;
    ((System.ComponentModel.ISupportInitialize)(this.axFP_CLOCK)).EndInit();

同样,我尝试在 Web 应用程序中连接,但它显示错误:Webform1:

 public AxFP_CLOCKLib.AxFP_CLOCK axFP_CLOCK;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                bool bRet;
                string ip= "192.168.1.109";
                int nPort = Convert.ToInt32(5005);
                int nPassword = Convert.ToInt32(0);
                axFP_CLOCK = new AxFP_CLOCKLib.AxFP_CLOCK();
                bRet = axFP_CLOCK.SetIPAddress(ref ip, nPort, nPassword);
                if (!bRet)
                {
                    Response.Write("success");
                }

                else
                {
                    Response.Write("failure");
                }
            }
        }

它抛出错误为

ActiveX 控件“87733ee1-d095-442b-a200-6de90c5c8318”无法实例化,因为当前线程不在单线程单元中。

DLL:

 public virtual bool SetIPAddress(ref string lpszIPAddress, int dwPortNumber, int dwPassWord)
    {
      if (this.ocx == null)
        throw new AxHost.InvalidActiveXStateException(nameof (SetIPAddress), AxHost.ActiveXInvokeKind.MethodInvoke);
      return this.ocx.SetIPAddress(ref lpszIPAddress, dwPortNumber, dwPassWord);
    }

任何人都可以帮助我纠正这个错误吗?

标签: c#asp.netbiometrics

解决方案


该错误消息表明您使用的 ActiveX 控件需要 STA(单线程单元)状态。可以通过使用Thread.SetApartmentState()方法设置对应线程的单元状态。

假设您已经创建了一个Thread这样的包装 ActiveX 实例:

var thread = new Thread(() => {
    // other running processes inside thread
    Application.Run();
});

然后你应该在使用之前将该线程的单元状态指定给 STA( ApartmentState.STA) Start()

thread.SetApartmentState(ApartmentState.STA);
thread.Start();

此问题背后的原因是大多数 .NET 后台线程(或工作 API)将创建新线程作为多线程单元状态 (MTA),而 ActiveX 控制线程通常在 STA 模式下实例化。

相关问题:

单线程单元 - 无法实例化 ActiveX 控件


推荐阅读