0

I am trying to learn asynchronous programming (C#/WPF) and I cant seem to understand some things, so I started with a simpler example but I am still stuck.

Example: Adds 2 lines of texts to a textbox, and shows the time it took, on the event of a button press.

This is the code:

private async void b1_Click(object sender, RoutedEventArgs e)
{
    txtb1.Text = "";

    var watch = System.Diagnostics.Stopwatch.StartNew();

    await writeintxtbx();

    watch.Stop();
    var elapsedtm = watch.ElapsedMilliseconds;

    txtb1.Text += $"TOTAL TIME {elapsedtm} \n\n\n";
}

private async Task writeintxtbx()        
{
   await Task.Run(() => Task1());
   await Task.Run(() => Task2());
}

private void Task1() 
{
    txtb1.Text += $"Task 01 Done \n\n";
}

private void Task2() 
{
    txtb1.Text += $"Task 2 done \n\n";
}

This is the error I am getting:

]ERROR I AM GETTING]1

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
Fiona
  • 77
  • 5
  • 1
    Does this answer your question? [The calling thread cannot access this object because a different thread owns it](https://stackoverflow.com/questions/9732709/the-calling-thread-cannot-access-this-object-because-a-different-thread-owns-it) – Scott Jun 19 '21 at 23:04
  • Please, check out the answer at the URL link below regarding **The calling thread cannot access this object because a different thread owns it** https://stackoverflow.com/questions/9732709/the-calling-thread-cannot-access-this-object-because-a-different-thread-owns-it – Thomson Mixab Jun 19 '21 at 23:14

1 Answers1

-2

UI elements (in Forms and in WPF) only allow you to work with themselves on the same thread in which they were created.
By default, this is the main thread of the application.
Every UI element in WPF (which is somewhat different in Forms) has a Dispatcher property that provides a thread manager from which you can interact with that UI element.
Since you are using asynchronous methods, you need to use something like the following code to reference the UI elements in them:

private DispatcherOperation Task1() 
{
    return txtb1.Dispatcher.BeginInvoke(() => txtb1.Text += $"Task 01 Done \n\n");
}

But it is much better to use bindings for working with WPF.
The value of the binding-source property can be changed on any thread. This greatly facilitates the interaction between data and UI elements. This is one of the features of WPF.
In the best possible way, all the features, tools, advantages of WPF Solutions are used if it is an implementation of the MVVM pattern.

EldHasp
  • 6,079
  • 2
  • 9
  • 24