簡體   English   中英

InvalidOperationException:調用線程必須是STA,因為許多UI組件都需要STA

[英]InvalidOperationException: The calling thread must be STA, because many UI components require this

您可以在SO上找到很多類似的問題,但是沒有一個問題(如我所見)涵蓋了您的邏輯必須返回某些東西的情況。

在此代碼示例中,我有一個簡單的CustomMessageBox(它是一個窗口),它必須返回用戶輸入的內容。

public class CustomMessageBox  
{
  private string Value 
  {
      get 
      {
          return txt_box.Text;
      } 
  }

  private CustomMessageBox ()
  {
      InitializeComponent();
  }

  public static string Show(string caption = "Enter data")
  {
      CustomMessageBox cmb = new CustomMessageBox ();
      cmb.txt_block.Text = caption;

      cmb.ShowDialog();

      return cmb.Value;
  }
}

因此,當BackgroundWorker調用的Show方法時,構造函數嘗試執行時會在第一行引發異常。 異常消息是

An exception of type 'System.InvalidOperationException' occurred in 
PresentationCore.dll but was not handled in user code


Additional information: The calling thread must be STA,  
because many UI components require this.

沒什么新鮮的,但是我找不到解決此問題的方法,也無法使線程成為STA。 Show方法簽名必須很清楚-接受字符串並返回字符串。

這樣的事情通常必須如何解決?

您不能從后台工作程序調用UI組件。 那是造成您問題的最直接原因。 必須從UI線程創建所有UI組件並與之交互。 這就是為什么在某些情況下我們有些瘋狂的邏輯來調用UI組件上的操作-應用程序中僅運行一個UI線程。

需要重新設計需要從后台流程填充UI元素的程序,以便將操作分為兩個或多個工作單元,從而消除了從后台操作UI的要求。

請參閱WPF和后台工作程序,並且調用線程必須是STA

public static string Show(string caption = "Enter data")
{
    Application.Current.Dispatcher.Invoke(new Action(() =>
    {
        CustomMessageBox cmb = new CustomMessageBox();
        cmb.txt_block.Text = caption;
        cmb.ShowDialog();
    }));
    return cmb.Value;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM