C#

Be careful using anonymous delegates across threads

[UPDATE]: It has been pointed out to me that the premise of this article is wrong. The compiler specifically avoids this problem by hoisting the captured variables into an inner class of which the generated method is also an instance member, and creating a new instance of this class for each call. I'm not sure what bug I ran into that causes the behaviour I denounced, or whether it was simply sloppy handling of reference types on my part -- but I feel particularly stupid having vaguely remembered "inner classes" from reading Raymond Chen's fine explanation of this over a year ago, yet not having checked it before posting this article. Nonetheless, I shall let the article remain as a reminder of the code that this wonderful feature saves you from having to write. Also, the queue/lock-based code may still be useful when one needs data passed to the GTK thread in a guaranteed order.

Anonymous delegates are incredibly useful, especially in that they can "capture" variables from a parent scope. Used within a single thread, they are very easy to understand. However, if you're using them to pass data across threads, you need to understand how the variable capture works.

Consider the following code snippet, in which the "data" variable is captured from the delegate's parent scope.

void ProcessIncomingData (string data)
{
	Gtk.Application.Invoke (delegate (object sender, EventArgs e) {
			textBuffer.AddText (data);
		});
}

What's wrong with this?

It lives!

The inbound (Mono -> Gecko) C++ DOM function is working fine and I can recieve a C# call in JavaScript; now I just need to pass it off to the actual function.

There was a bit of trouble initially as I couldn't obtain an nsIWebBrowser pointer from gtk_moz_embed_get_nsIWebBrowser. This turned out to be because the Gecko# WebControl hadn't been shown yet (i.e. window.ShowAll()), but I didn't figure this out as other functions like gtk_moz_embed_get_location worked fine.

Here's Blagovest Dachev's XUL GUI demo hosted in my container, with a simple C#->JS call demonstration. For anyone who hasn't seen the Mono Summer of Code page, Blago's working on the Mozilla half of this project.

Gecko# interaction

Implementing the ASP.NET GUI designer with Mozilla's Gecko web rendering engine is an obvious decision: it's open-source, has strong standards support and a large feature set, is highly extensible and flexible thanks to its XPCOM component system, and using Gecko# it can be embedded in a GTK# GUI. Mozilla is becoming an application platform, with XUL for declaratively writting GUIs, and JavaScript for program logic.

Gecko# wraps GtkMozEmbed, which is a C GTK widget, hiding Mozilla's native C++. Understandably this widget isn't bloated by wrapping the Mozilla DOM or other internals: it claims to exposes enough functionality for "about 80% of uses". Essentially this means a basic web browser.

Syndicate content