How to access the main thread from the main thread

Asked

Viewed 109 times

0

I wonder if it is possible to call a method using a thread from another thread. The reason is that there are methods that can only be called from the main thread, and I need to call them in another thread.

1 answer

0

The Main thread will need invocation, during debugging will show an error when you operate a Cross-Thread operation, but this exception will be non-existent at the time of Release.

If your Thread is a Form, you can invoke with this code:

if (InvokeRequired)
{
    this.Invoke(new Action(() => SuaFuncao()));
    return;
}

Be it SuaFuncao() the method Thread would run.

In . NET 2.0 would be the equivalent of:

this.Invoke((MethodInvoker) delegate {MyFunction();});

For Console applications:

var mydelegate = new Action<object>(delegate(object param)
{
    Console.WriteLine(param.ToString());
});
mydelegate.Invoke("test");

Source

Browser other questions tagged

You are not signed in. Login or sign up in order to post.