Can I use Awesomeium within a web application?

2020-02-12 14:57发布

问题:

I'm trying to render a html code to export it to an image and then use that image to put it in a pdf document. I'm doing all in an asp.net/C# web application. The problem I'm having is that when I do that more than one time it give me this error:

You are attempting to re-initialize the WebCore. The WebCore must only be initialized once per process and must be shut down only when the process exits.

This is my code:

WebCore.Initialize(new WebConfig(), false);
using (WebView webView = WebCore.CreateWebView((pdfWidth - 80).ToString().ToInt() + 20, (pdfHeight / 2).ToString().ToInt() + 20))
{
    webView.LoadHTML(html);

    while (webView.IsLoading || !webView.IsDocumentReady)
                WebCore.Update();

    Thread.Sleep(1100);
    WebCore.Update();

    string fileName = Server.MapPath("result." + DateTime.Now.Second.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Millisecond.ToString() + ".png");
    BitmapSurface surface = (BitmapSurface)webView.Surface;
    surface.SaveToPNG(fileName, true);

    WebCore.Shutdown();
}

I figure that I can't initialize the WebCore every time the web page render, so I put it in the Global.asax. After doing this, when I'm debugging, another error came up:

Attempted to read or write protected memory. This is often an indication that other memory is corrupt. The current thread is not currently running code or the call stack could not be obtained.

Any ideas how can I do this?

Thanks

回答1:

Short answer: yes, you can.

BUT according to the WebCore documentation:

Note that Awesomium and Awesomium.NET are not thread-safe. All API members should be called from the thread that initialized the WebCore (see Initialize(WebConfig)) or created the first WebView, WebSession or technology specific WebControl.

Also look at the Exceptions section of WebCore.Update() method description:

System.AccessViolationException - You attempted to access the member from a thread other than thread where WebCore was created.

Thus considering that every request in web application is generally processed in different thread, AccessViolationException is a documented feature.

Therefore your task here is to guarantee that all Awesomium calls will be processed in a special dedicated thread. The thread should live on application level and its access has to be shared between requests. Technically, you need to write a kind of Message Loop or Synchronization Context where you will be able to push your delegate, Action or Func with Awesomium code to provide its execution only in this thread.



回答2:

probably you need to call the webview.invoke or webview.begininvoke and you are going to need to create a delegate to access the webview that was created before the webcore.initialize in another thread, I would use a singleton pattern to use the same webview instance.