问题
I want to get source of web page in CEF3/Xilium CefGlue rom non-UI thread (offscreen browser)
I do this
internal class TestCefLoadHandler : CefLoadHandler
{
protected override void OnLoadStart(CefBrowser browser, CefFrame frame)
{
// A single CefBrowser instance can handle multiple requests for a single URL if there are frames (i.e. <FRAME>, <IFRAME>).
if (frame.IsMain)
{
Console.WriteLine("START: {0}", browser.GetMainFrame().Url);
}
}
protected override void OnLoadEnd(CefBrowser browser, CefFrame frame, int httpStatusCode)
{
if (frame.IsMain)
{
MyCefStringVisitor mcsv = new MyCefStringVisitor();
frame.GetSource(mcsv);
Console.WriteLine("END: {0}, {1}", browser.GetMainFrame().Url, httpStatusCode);
}
}
}
class MyCefStringVisitor : CefStringVisitor
{
private string html;
protected override void Visit(string value)
{
html = value;
}
public string Html
{
get { return html; }
set { html = value; }
}
}
But the call to the
GetSource(...)is asynchronous, so I need to wait for the call to occur before trying to do anything with result.
How can I wait for the call to occur?
回答1:
According to Alex Maitland tip that said to me that I can be able to adapt the CefSharp implementation (https://github.com/cefsharp/CefSharp/blob/master/CefSharp/TaskStringVisitor.cs) to do something similar.
I do this :
protected override async void OnLoadEnd(CefBrowser browser, CefFrame frame, int httpStatusCode)
{
if (frame.IsMain)
{
// MAIN CALL TAKES PLACE HERE
string HTMLsource = await browser.GetSourceAsync();
Console.WriteLine("END: {0}, {1}", browser.GetMainFrame().Url, httpStatusCode);
}
}
public class TaskStringVisitor : CefStringVisitor
{
private readonly TaskCompletionSource<string> taskCompletionSource;
public TaskStringVisitor()
{
taskCompletionSource = new TaskCompletionSource<string>();
}
protected override void Visit(string value)
{
taskCompletionSource.SetResult(value);
}
public Task<string> Task
{
get { return taskCompletionSource.Task; }
}
}
public static class CEFExtensions
{
public static Task<string> GetSourceAsync(this CefBrowser browser)
{
TaskStringVisitor taskStringVisitor = new TaskStringVisitor();
browser.GetMainFrame().GetSource(taskStringVisitor);
return taskStringVisitor.Task;
}
}
来源:https://stackoverflow.com/questions/29287430/xilium-cefglue-how-to-get-html-source-synchonously