我想从非UI线程(屏幕外浏览器)获取CEF3 / ChromiumFX中的网页源
我这样做
void loadHandler_OnLoadEnd(object sender, Chromium.Event.CfxOnLoadEndEventArgs e)
{
// Get HTML code
string htmlSource;
CfxStringVisitor sv = new CfxStringVisitor();
sv.Visit += ((se, ee) => { htmlSource = ee.String; });
browser.MainFrame.GetSource(sv);
}
但htmlSource
始终为NULL。
如何同步获取HTML源?
答案 0 :(得分:0)
基于CefSharp TaskStringVisitor实现(https://github.com/cefsharp/CefSharp/blob/master/CefSharp/TaskStringVisitor.cs)
public class TaskStringVisitor : CfxStringVisitor
{
private readonly TaskCompletionSource<string> taskCompletionSource;
public TaskStringVisitor()
{
taskCompletionSource = new TaskCompletionSource<string>();
this.Visit += TaskStringVisitor_Visit;
}
void TaskStringVisitor_Visit(object sender, Chromium.Event.CfxStringVisitorVisitEventArgs e)
{
try
{
taskCompletionSource.SetResult(e.String);
}
catch (Exception ex)
{
taskCompletionSource.SetException(ex);
}
}
public Task<string> Task
{
get { return taskCompletionSource.Task; }
}
}
public Task<string> GetSourceAsync()
{
TaskStringVisitor taskStringVisitor = new TaskStringVisitor();
browser.MainFrame.GetSource(taskStringVisitor);
return taskStringVisitor.Task;
}
async void loadHandler_OnLoadEnd(object sender, Chromium.Event.CfxOnLoadEndEventArgs e)
{
// Get HTML code
string HTMLsource = await GetSourceAsync();
}