Calling another class method in a Task c#

Asked

Viewed 375 times

-1

I’m trying to make a task call from a method of another Class:

Diretorios diretorios = new Diretorios();
await Task.Run(() => diretorios.CopiaDiretorios(tbxVersaoAtual.Text, tbxServerCopia.Text));

Only I get the following Exception:

System.Invalidoperationexception: 'The call thread cannot access this object because it belongs to a different thread.'

It’s really not possible to do what I’m trying to do?

I really need to wait for the execution of this method before proceeding with the execution and I can’t block the Thread UI so I need to run a Task.

PS: The call method is async and the called method is returning a Task as it should be.

Some solution?

  • Is Windows Forms?

  • No, I’m using WPF.

2 answers

1

The answer is basically the same as this question here: Modify visual element by another thread

The difference is that, in WPF, each control has a property called Dispatcher which contains the elements necessary to make the Invoke.

Functional example:

private void button_Click(object sender, RoutedEventArgs e)
{
    Task.Run(() =>
    {
        Thread.Sleep(5000);
        SetText(textBox, "Qualquer texto");
    });
}

public static void SetText(TextBox txtbox, string texto)
{
    if (txtbox.Dispatcher.CheckAccess())
        txtbox.Text = texto;            
    else
        txtbox.Dispatcher.Invoke(() => txtbox.Text = texto, DispatcherPriority.Normal);
}
  • In this case, the Dispatcher serves to change properties of objects within different threads from which they were created right? In my case I need to call a method of another class as a Task. notice that I am instantiating a new class and trying to call its method in a Task. How could I use Dispatcher.Invoke in this case?

0

RESOLVED!

In fact I had to change the return of the method I was called from Void to Task.

After doing so it worked.

Anyway, thank you so much

Browser other questions tagged

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