[Gtk-sharp-list] Multi-threading and GTK#

Davy Brion ralinx@gmail.com
Tue, 20 Jul 2004 22:29:58 +0200


On Tue, 20 Jul 2004 18:10:32 +0300 (EEST), Andrei Ivanov
<andrei.ivanov@ines.ro> wrote:
> 
> Maybe you should send it to the list, I want to see some examples.
> Thanks.

here's an example where i took out all of the non ThreadNotify related stuff

i have class which inherits from the VPaned class:

public class DownloadList : VPaned
{
	private Queue m_queNewDownloads;
	private ThreadNotify m_thnThreadNotify;

	public DownloadList() : base()
	{
		m_thnThreadNotify = new ThreadNotify( new ReadyEvent(UpdateList) );
		m_queNewDownloads = new Queue();
	}

	public void AddDownload(Download aDownload)
	{
		Monitor.Enter(m_queNewDownloads);
		m_queNewDownloads.Enqueue(aDownload);
		Monitor.Exit(m_queNewDownloads);
	}

	public void Update()
	{
		m_thnThreadNotify.WakeupMain();
	}

	private void UpdateList()
	{
		// update the GTK objects here to show the new information
	}
}


this class is being used from another class, which will regularly want
the GUI to update itself based on new information it receives:

public class Main
{
	private DownloadList m_dlDownloadList;
	private IRCLeech m_objIrcLeech;

	public Main()
	{
		m_objIrcLeech = IRCLeech.GetReference();
		m_objIrcLeech.DownloadOffered += new
DownloadOfferedEventHandler(OnDownloadOffered);
		m_dlDownloadList = new DownloadList();
	}

	private void OnDownloadOffered(ServerConnection sender,
DownloadOfferedEventArgs args)
	{
		m_dlDownloadList.AddDownload(args.Download);
		m_dlDownloadList.Update();
	}
}

the code in the Main class will run in a seperate thread (ie: not the
GTK Thread), and it will often call the AddDownload and Update method
of the DownloadList class.  When it calls the Update method, it uses
the WakeupMain method to tell the GTK thread that it needs to do
something.  The important part is that you only access the GTK objects
from within the GTK thread, never from another thread.  So whenever
you need to update your GUI, you just have to call the WakeupMain
method, so you can update your GTK objects from within the GTK
thread... i pass along the info that needs to be updated by using
Queue objects or that kinda stuff.  The Queue object will be accessed
by both threads but that's not a problem as long as you lock it
properly.

i hope this is clear... i know i'm not showing a lot of code but there
really isn't much more to it and i wanted to make sure that this
example only included the ThreadNotify related stuff so it would
hopefully be as clear as possible.

HTH