ActiveX控件无法实例化,因为当前线程不在单线程单元中 - 来自WebBrowser

时间:2016-08-05 06:10:02

标签: c# multithreading oauth-2.0 resharper

我想在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=", "<");
    }

当我这样做时,我收到以下错误

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()

0 个答案:

没有答案