我已经扫描了标签[cefsharp],我问的问题是以类似的形式出现的(请重新考虑重复的问题行动) .

我无法解决我认为应该是一个简单的请求 . 在浏览器控件中获取页面的html源并同步与winform控件交互 .

我在异步方面很弱,但设法通过我从这个标签[cefsharp]获得的几种方式来获取源代码 . 但是,任何与winform控件的交互都是从异步事件触发的,其中任何后续方法中的异步事件都会调用异步"mode",因此任何winform控件交互 .

Example 1:

private async void Browser_LoadingStateChanged(object sender, 
                                        CefSharp.LoadingStateChangedEventArgs e)
{
    if (!e.IsLoading)
    {
        //-- WORKS, but ...
        string html = await Task.Run(Browser.GetSourceAsync);


        //-- .. when calling other methods which interact with winform controls,
        //-- I have to do so in the following way because I am not on the UI thread.
        //-- therefore every control needs a block like this
        if (InvokeRequired)
        {
            this.Invoke(new MethodInvoker(delegate
            {
                txtSource.Text = html;
            }));
        }
        else
        {
            txtSource.Text = html;
        }
    }
}

Example 2: 我部分工作的另一个例子是这种方法 . 但是,通过按钮单击调用可以正常工作,而浏览器事件则不会

public string GetSource()
{
    string result = null;

    if (Browser.IsBrowserInitialized && !Browser.IsDisposed && !Browser.Disposing)
    {
        Task<string> task = Browser.GetSourceAsync();
        var complete = task.ContinueWith(t =>
        {
            if (!t.IsFaulted)
            {
                result = t.Result;
            }
        }, TaskScheduler.Default);
        complete.Wait();

    }
    return result;
}

private void button1_Click(object sender, EventArgs e)
{
    //-- WORKS
    txtSource.Text = GetSource();
}

private void Browser_LoadingStateChanged(object sender, 
                                        CefSharp.LoadingStateChangedEventArgs e)
{
    if (!e.IsLoading)
    {
        //-- DOES NOT WORK. Hangs on waiting for the complete.Wait();
        //-- note: this method is not async and neither the button too.
        txtSource.Text = GetSource();
    }
}