Archive for the ‘.NET / C#’ Category

Well, I’ve just spent way more time than necessary debugging an issue I had with a TreeView not being correctly updated and freezing the whole application.

Unlike WPF (and also I think Winforms), Gtk# does not complain when a GUI object is accessed or modified from a separate thread, so I incorrectly assumed that the issue wasn’t related to cross thread safety. As it turns out, my assumption was wrong (they usually are ;) ).

In order to alter Gtk object from a separate thread, a method similar to the WPF Dispatcher can be used:

Gtk.Application.Invoke(delegate {
      randomGtkWindow.Title = "blah";
});

Now, if we don’t invoke on the original Gtk thread, sometimes it will work, sometimes it won’t, with quite disastrous results. From what I’ve experienced so far, generally no error is thrown and if it is, then it’ll be quite cryptic.

Maybe the Gtk# developers should cause Gtk objects to throw an exception when accessed in a different thread?

I’ve come across a rather interesting feature of IronPython and the DLR (forgive me if this is old news :P ) which I never previously knew about and would make an interesting addition to my planned Facebook XMPP client; the ability to execute embedded IronPython from any .NET language (even IronPython itself).

using System;
using System.Collections.Generic;
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;

namespace ConsoleApplication3
{
	class Program
	{
		static void Main(string[] args)
		{
			Dictionary<int, int> bar = new Dictionary<int, int>();

			ScriptEngine engine = Python.CreateEngine();
			ScriptScope scope = engine.CreateScope();
			scope.SetVariable("bar", bar);

			string script = @"

from System import Console

foo = 'Hello from IronPython!'
Console.Title = foo

for i in range(0, 10):
	bar.Add(i, i**2)";

			engine.Execute(script, scope);
			Console.WriteLine(scope.GetVariable("foo"));

			foreach (KeyValuePair<int, int> kvp in bar)
			{
				Console.WriteLine("{0}^2 = {1}", kvp.Key, kvp.Value);
			}

			Console.ReadKey();
		}
	}
}

This is a great way to allow custom user defined scripts to alter a program without changing the actual code base. The embedded Python has complete access to the .NET library, likewise the calling C# has complete access to the embedded script.

I can’t see much practical use for this in a chat client, but I’m working on it :P