Search code examples
c#multithreadingoauth-2.0resharper

ActiveX control cannot be instantiated because the current thread is not in a single-threaded apartment - from WebBrowser


I want to call the following code from within a unit test in Resharper Test runner.

    /// <summary>
    /// Function to return the OAuth code
    /// </summary>
    /// <param name="config">Contains the API configuration such as ClientId and Redirect URL</param>
    /// <returns>OAuth code</returns>
    /// <remarks></remarks>
    [STAThread]
    public static string GetAuthorizationCode(IApiConfiguration config)
    {
        //Format the URL so  User can login to OAuth server
        string url =
            $"{CsOAuthServer}?client_id={config.ClientId}&redirect_uri={HttpUtility.UrlEncode(config.RedirectUrl)}&scope={CsOAuthScope}&response_type=code";

        // Create a new form with a web browser to display OAuth login page
        var frm = new Form();
        var webB = new WebBrowser();
        frm.Controls.Add(webB);
        webB.Dock = DockStyle.Fill;

        // Add a handler for the web browser to capture content change 
        webB.DocumentTitleChanged += WebBDocumentTitleChanged;

        // navigat to url and display form
        webB.Navigate(url);
        frm.Size = new Size(800, 600);
        frm.ShowDialog();

        //Retrieve the code from the returned HTML
        return ExtractSubstring(webB.DocumentText, "code=", "<");
    }

When I do I get the following error

System.Threading.ThreadStateException : ActiveX control '8856f961-340a-11d0-a96b-00c04fd705a2' cannot be instantiated because the current thread is not in a single-threaded apartment.
   at System.Windows.Forms.WebBrowserBase..ctor(String clsidString)
   at System.Windows.Forms.WebBrowser..ctor()

Solution

  • The issue occurs when we are creating a new Form over a non UI thread. (Threads can be verified from Debug->Windows->Threads section)

    I got the same issue and on doing some analysis, found that the new form was getting created on a new thread and not on the mail STA Thread.

    In order to resolve this, I called the method which is creating the new form using the Dispatcher class present in the .NET System.Windows.Threading namespace as follows:

      var dispatcher = Dispatcher.CurrentDispatcher;
      dispatcher.Invoke(new Action(() =>
      {
      isConnectedSuccessfully = UserInfoService.Login();
      }));
    

    Call your method from dispatcher, and it will ensure that the form gets created on the same main UI thread.

    This solved the issue for me. :-)