How do I raise an event on spun thread?

  • Thread starter Thread starter Chris Williamson
  • Start date Start date
C

Chris Williamson

Could anyone suggest the best method to create a thread that will process
events?

I need to create a thread that calls the SQLDMO.Backup.SQLBackup method
(which is asyncrhonous). SQLBackup raises the Complete event, but I need it
to be executed by the spun thread, not the main form's thread. After the
backup is done (after calling SQLBackup for each database - syncrhonously)
the thread will raise an event to the main form.

Raising the event on the main form and passing it to the thread is not
legitamate. I cannot rely on the main form as this is going into an object
and I cannot rely there being a form (it may be a console app, or the form
may be busy doing something else that will hold up beginning a backup on
another database).

I've gotten around this by creating a hidden form within my backup object
and hidden it. But I see that as wasted resources and possible trouble down
the road (console app, service, or asp.net app). Is there a better way for
me to do this? Could I get away with inheriting
System..ComponentModel.Component?

Thank you,

Chris Williamson
 
Thank you for your reponse.

This is half of what is going on. My class does create a thread and raises
an event to the calling code as you described. That event is handled by the
thread of the calling code's form - as it should be. However, my thread is
calling an async process that raises an event. This event is also handled
by the thread of the calling code's form - not the intended procedure.

My class is creating a thread and will be calling the async process 10
times, but can't call the 2nd until the first throws the complete event. In
similar projects, I've switched to blocking calls instead of an async
method. Unfortunately, sqldmo doesn't provide a blocking call.

Thank you,

Chris Williamson
 
Hi, Chris!

Ok, I'm going to create a pseudo-code sample of the two classes how
I would design them. It's possible that I'm not understanding your
problem properly, so I apologize if this doesn't get it. Again, this is
untested, it probably wouldn't even compile.

class Backup
{
public event EventHandler BackupComplete;

public void DoBackup ()
{
int handle = SqlLibrary.FirstAsyncCall ();
while (false == SqlLibrary.AsyncCallComplete (handle))
Thread.Sleep (50);
handle = SqlLibrary.SecondAsyncCall ();
while (false == SqlLibrary.AsyncCallComplete (handle))
Thread.Sleep (50);
this.BackupComplete (this, new EventArgs);
}

public void StartBackupThread ()
{
Thread thread = new Thread (new ThreadStart (this.DoBackup));
}
}

class Form
{
public void BackupDoneEventHandler (object sender, EventArgs e)
{
this.BackupDoneFlag = true;
}

public void BackupButtonClick ()
{
Backup backup = new Backup ();
backup.BackupComplete += new EventHandler (this.BackupDoneEventHandler);
backup.StartBackupThread ();
}
}

Good luck!

Scott Wagner
Seisint, Inc.
 
Back
Top