invoking the execution of a function on another thread

J

Jon

Hi,

"THREAD_UI" = thread under which the UI controls were created.
"THREAD_XX" = another thread.
"FUNC_UI" = function that needs to run on THREAD_UI.

From THREAD_XX I need to start the execution of FUNC_UI, that needs to
run on THREAD_UI. Inside FUNC_UI, I will modify many controls present
on the form. Since I don't want to use Invoke() or BeginInvoke() for
each of those calls, this is why I thought it would be more efficient
if FUNC_UI run on THREAD_UI.

How, from THREAD_XX, can I invoke FUNC_UI to run on THREAD_UI ?

FUNC_UI is not tied to any single control. Invoke() and BeginInvoke()
are member methods of one control. Is there an elegant way to invoke
FUNC_UI without having to refer to a specific control?

Thank you very much,
Jon
 
M

Marc Gravell

One option is to pass an ISynchronizeInvoke into your code; any handy
Control will satisfy this, and it abstracts the way of calling Invoke
etc.

The other approach is to use the ambient sync-context; the running
form will set itself up as the sync-context:

SynchronizationContext ctx =
SynchronizationContext.Current;
if (ctx == null)
{ // no sync-context: execute directly
Foo();
}
else
{ // ask the sync-context to execute it for us
ctx.Send(delegate { Foo(); }, null);
}

Marc
 

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