how to use async in Dispatch.StartTimer?

mc 3,701 Reputation points
2023-04-08T09:28:31.0633333+00:00
Dispatcher.StartTimer(TimeSpan.FromSeconds(10), () =>
        {
			//image1.ScaleTo(1.7, 5000).Wait();
			//image1.ScaleTo(1, 5000).Wait();
            return true;
        });

But I can not use await in StartTimer?

.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
2,962 questions
0 comments No comments
{count} votes

Accepted answer
  1. VasimTamboli 4,420 Reputation points
    2023-04-08T11:57:03.9766667+00:00

    You are correct that await cannot be used within the lambda function passed to Dispatcher.StartTimer because it expects a synchronous delegate that returns a boolean value indicating whether the timer should be restarted.

    To use async code within the timer callback, you can define an async method that performs the desired operation and returns a Task<bool> that indicates whether the timer should be restarted. You can then pass this method as the callback to Dispatcher.StartTimer.

    Here is an example:

    csharp Copy code private async Task<bool> DoSomethingAsync() { await image1.ScaleTo(1.7, 5000); await image1.ScaleTo(1, 5000); return true; }

    Dispatcher.StartTimer(TimeSpan.FromSeconds(10), () => { DoSomethingAsync(); return true; }); In this example, DoSomethingAsync is an async method that performs the desired operation, and returns a Task<bool> that always completes successfully with the value true. The timer callback simply calls DoSomethingAsync and returns true to restart the timer.

    0 comments No comments

0 additional answers

Sort by: Most helpful