【问题标题】:ASP.NET WCF Service error "The calling thread must be STA, because many UI components require this. "?ASP.NET WCF 服务错误“调用线程必须是 STA,因为许多 UI 组件都需要这个。”?
【发布时间】:2013-03-21 07:07:08
【问题描述】:

我有一些使用 .net 程序集的窗口工作流。我正在从这些工作流窗口访问一些硬件。我通过虚拟目录方法在 IIS 上发布的 XYZ 服务对这一切都有帮助。 现在我想从我的 .Net Web 应用程序中使用这些工作流。我做了一个 wcf 服务和一个 web 客户端。我的 wcf 服务(根据 Web 客户端请求)加载工作流(成功)并尝试执行。

问题是当我调用加载的工作流的执行时,它给出了异常“调用线程必须是STA,因为许多UI组件都需要这个。”

【问题讨论】:

    标签: asp.net wcf iis-7 sta


    【解决方案1】:

    如果您从非单线程单元线程的线程中使用 WinForms/WPF 对象,您将收到此异常。为了使用 WCF 服务中的这些对象,您需要创建一个新线程,将该线程上的单元状态设置为 STA,然后启动该线程。

    我的简单示例采用一个字符串并根据 WPF 文本框的拼写检查功能对其进行检查:

    public bool ValidatePassword(string password)
    {
        bool isValid = false;
    
        if (string.IsNullOrEmpty(password) == false)
        {
            Thread t = new Thread(() =>
            {
                System.Windows.Controls.TextBox tbWPFTextBox = new System.Windows.Controls.TextBox();
    
                tbWPFTextBox.SpellCheck.IsEnabled = true;
                tbWPFTextBox.Text = password;
                tbWPFTextBox.GetNextSpellingErrorCharacterIndex(0, System.Windows.Documents.LogicalDirection.Forward);
    
                int spellingErrorIndex = tbWPFTextBox.GetNextSpellingErrorCharacterIndex(0, System.Windows.Documents.LogicalDirection.Forward);
    
                if (spellingErrorIndex == -1)
                {
                    isValid = true;
                }
                else
                {
                    isValid = false;
                }
    
            });
    
            t.SetApartmentState(ApartmentState.STA);
            t.Start();
            t.Join();
        }
    
        return isValid;
    }
    

    您也可以参考此 S.O.邮政: How to make a WCF service STA (single-threaded)

    以及答案中的链接: http://www.netfxharmonics.com/2009/07/Accessing-WPF-Generated-Images-Via-WCF

    【讨论】:

      【解决方案2】:

      我找到了这个

      STAthread

      你也可以使用

      解决你的问题
      [STAthread]
      private void yourMethod()
      {
      //Call the execution here
      }
      

      或者尝试这样做:

      private void yourMethod()
      {
           Thread t = new Thread(here delegate your method where you call the execution);
           t.SetApartmentState(ApartmentState.STA);
           t.Start();
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-14
        • 2017-02-20
        • 1970-01-01
        相关资源
        最近更新 更多