Table of Contents
Using WebView Directly without UI

While you can use WebView class directly, internally the WebView class relies on Windows handle and messages to function. The window handle of the WebView must be created by a thread that runs a message loops and dispatches Windows messages. This is not a problem for an UI application because the main thread of an UI application always runs a message loop in order to handle user input. However this can be a problem if you use WebView in a server application, such as an ASP.NET application, since such applications do not run a Windows message loop.

The ThreadRunner class is introduced to address this issue. In a server application, you can use the ThreadRunner to create and "run" WebView objects. Each ThreadRunner runs a message loop in a separate thread. When you use the ThreadRunner class to create a WebView, the WebView is associated to that thread. The following code demonstrates how to create a WebView through a ThreadRunner:

//Create a ThreadRunner object
ThreadRunner threadRunner = new ThreadRunner();

//Create a WebView through the ThreadRunner
WebView webView = threadRunner.CreateWebView();

Once a WebView is created through the ThreadRunner, any action on that WebView must carry out in the corresponding ThreadRunner's thread. This can be achieved through the ThreadRunner's Send or Post method. For example, the following code loads Google's home page and then capture a screen-shot:

threadRunner.Send(() =>
{
    //Load Google's home page
    webView.LoadUrlAndWait("http://www.google.com");
    
    //Capture screens-hot and save it to a file
    webView.Capture().Save(screen_shot_file_name);
});

Send will not return until the action finishes. On the other hand, Post will return immediately.

Please keep the following in mind when you use the ThreadRunner class:

  • You can create multiple WebView objects using a single ThreadRunner. There is no need to create a separate ThreadRunner object for each WebView;
  • When you no longer needs the WebView, you must call the WebView's Destroy method to destroy the WebView. Destroy should be called directly, not through Send or Post method;
  • When you no longer needs the ThreadRunner object, call the ThreadRunner's Stop or Dispose method to stop the thread associated to the ThreadRunner object. Once a ThreadRunner is stopped, it can no longer be used;