Thanks to VladD, who answered me here last time - Playing animation from the background thread , as well as a bunch of different topics in other forums, I kind of began to better understand the principle of working with wpf, but on the other hand I got even more confused. In general, my goal is still to start the animation from the background thread. Now I have determined that the animation call code in the background thread is working, but I can’t understand why. In my program, there is an asynchronous method call that makes a post-request and returns the answer:

async Task<string> PostMethod() { HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subKey); HttpResponseMessage response; string json; using (ByteArrayContent content = new ByteArrayContent(Webcam.lastSnapshot)) { content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); response = await client.PostAsync(uriBase, content); json = await response.Content.ReadAsStringAsync(); } return json; } 

And there is a function in which PostMethod and the animation itself are called, respectively.

  async void Func() { string json = await PostMethod(); ColorAnimation anim = new ColorAnimation(); //Π—Π΄Π΅ΡΡŒ всякиС настройки Π°Π½ΠΈΠΌΠ°Ρ†ΠΈΠΈ Rect.InvokeAsync(async()=>{ Rect.BeginAnimtion(SolidColorBrush.ColorProperty, anim);}); } 

If I understand correctly, await pauses the execution of a method until asynchronous code runs after await. But for me, for some reason, in the output window, the notification about the end of the stream comes later than the Rect.InvokeAsync method is called, with seconds for 5-7. Therefore, I can conclude that the error while playing the animation is somehow related to PostMethod, but I cannot understand how. Please help to understand!

  • What is Rect and where does it get its InvokeAsync method? - Pavel Mayorov
  • And how do you call Func ()? - Pavel Mayorov
  • Sorry, missed contacting Dispatcher. Rect - a rectangle (class Rectangle). Func is called by means of a "reaction" to an event. - reinhart

2 answers 2

Read the answer to this question from Async and Await. The context of synchronization and execution. The finite automaton. C #

It appears that you are capturing the synchronization context of a non-UI stream, which you do not need.

    See, the message on the completion of the thread and should not appear immediately.

    Task is usually executed not in a new thread, but on a thread pool. Accordingly, the completion of Task 'and does not mean the end of the thread.


    The problem that is immediately apparent is that your animation is created in the background thread, and this is wrong. Do this:

     dispatcher.InvokeAsync(() => { ColorAnimation anim = new ColorAnimation(); //Π—Π΄Π΅ΡΡŒ всякиС настройки Π°Π½ΠΈΠΌΠ°Ρ†ΠΈΠΈ Rect.BeginAnimation(SolidColorBrush.ColorProperty, anim); }); 
    • What an annoying mistake) Thank you guys! - reinhart