Async/Await Snipped: Avoid multiple calls by using delays

When you work with async and await keywords in C#. You sometimes want to avoid unnecessary calls, that are caused by multi-threading. Here is a simple snipped that works fine…

Scenario: Last Wins

        Task _delayTask;

        async void StartWithDelay()
            // keep a local copy and a member copy of the task
            Task delayTask = _delayTask = Task.Delay(1000);

            // await the delay
            await delayTask;

            // is it still the same task (or is there a new one)
            if(delayTask == _delayTask) 
                // do your work here...
Tagged , , ,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: