[Mono-list] Detecting Thread Finish

Aaron Bockover aaron.lists@aaronbock.net
Mon, 11 Apr 2005 11:01:34 -0400


Hello,

I was wondering if there is a way to detect when a thread is finished/no
longer exists, apart from some kind of timeout or idle callback that
checks the thread instance itself. 

I have a multi-threaded app in which there are a few threads, spawned by
certain user interaction. These threads all need to access a SQLite
database. I've written a DB layer that has a hashtable of
IDbConnections, where a thread instance is the table key. This is
because SQLite is not thread safe, so each new thread needs its own
connection to the database. This works beautifully:

...
private Hashtable threadConnections;
...

private IDbConnection dbcon
{
  get {	
    return Connect();
  }
}

public Database(string dbname, string dbpath)
{
  ...
  threadConnections = new Hashtable();
  Connect();
  ...
}

private IDbConnection Connect()
{
  if(threadConnections[Thread.CurrentThread] != null)
    return (IDbConnection)threadConnections[Thread.CurrentThread];
			
  IDbConnection conn = new SqliteConnection("URI=file:" + dbpath);
  conn.Open();

  threadConnections[Thread.CurrentThread] = conn;
  return conn;
}

public IDataReader Query(object query)
{
  IDbCommand dbcmd = dbcon.CreateCommand();
  dbcmd.CommandText = query.ToString();
  return dbcmd.ExecuteReader();
}

The problem is that at any given moment, threadConnections may have any
number of IDbConnection active instances whose keys are instances to
threads that no longer exist. I would assume that when the thread
finishes, the key would be null? Or would it? I haven't checked just
yet. If so, could this cause problems with the hashtable, since multiple
keys may end up being null?

I'd like to be able to tell immediately when the thread finishes to
close the associated connection in the hashtable. 

For example, add this to the connect method:

...
Thread.CurrentThread.Finished += OnThreadFinished;
...
private void OnThreadFinished(object o, EventArgs args)
{
  if(threadConnections[o] == null)
    return;
  ((IDbConnection)threadConnections[o]).Close();
}

Any help, ideas, direction, would be greatly appreciated. I'd really
like to avoid a timeout or idle callback to check the table periodically
for dead threads.

Thanks!

--Aaron Bockover