How to access the main thread from the main thread

0

I would like to know 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.

    
asked by anonymous 28.12.2017 / 22:40

1 answer

0
The main thread will need invocation, while debugging will show an error when you operate a cross-thread operation, but this exception will not exist at the time of the release.

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

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

Be SuaFuncao() the method that the Thread would execute.

In .NET 2.0 it 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");

Font

    
28.12.2017 / 23:33