fire an event in main thread context

G

Guest

Hi,

I create a class whitch creates a thread. When thread finish it has to fire
event. But I want to fire this event in the context of the thread that
created the class (usually main thread). For this I create a control in
context of the creator thread. But are there better techniques,like maybe
create a hidden window or something else ? this is code snippets i use now:

public class CDelay
{
Control Ctrl;

public delegate void RequestDone(object sender, RequestDoneArgs e);
public event RequestDone OnRequestDone;
public class RequestDoneArgs: EventArgs
{
Int32 FThreadId;

public RequestDoneArgs(Int32 ThreadId)
{
FThreadId = ThreadId;
}

public Int32 ThreadId
{
get { return FThreadId; }
}
}

public CDelay(Control Parent)
{
Ctrl = new Control();
Ctrl.Parent = Parent;

So in constructor Ctrl is created in thread context of the creator (Parent).
When I have to call event I use the normal Invokething:

RequestDoneArgs e = new
RequestDoneArgs(Thread.CurrentThread.ManagedThreadId);
if(OnRequestDone != null)
Ctrl.BeginInvoke(OnRequestDone, new object[] { this, e });

It works as a glance, but if there are better things ZI like to know of
course.
 
W

Willy Denoyette [MVP]

Unless you are willing to reinvent the wheel by coding what's happening when
calling Invoke, there aren't.
Not sure why you need to execute the eventhandler on the thread that created
the class, in general it's considered bad practice to affinitize handlers
with specific threads?

Willy.
 
G

Guest

Hi,
Not sure why you need to execute the eventhandler on the thread that created
the class, in general it's considered bad practice to affinitize handlers
with specific threads?

I'm just starting to play around with .NET once a while, so I dont know
mutch about thread safe programming yet, but I should think if I use a
class/component, and I create it in main thread then I dont expect that his
events will fire in a different thread context. Or am I wrong here ?

On the other hand I see mutch of things in NET is threading and blocking, so
maybe it is just a 'hangover' from me from the win32 programming :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top