Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create async Task<T> without run

How can I create a async Task but not run it right away?

private static async Task<string> GetString()
{
    await Task.Delay(5000);
    return "Finish";
}

Task<string> str = GetString();

This immediately starts the task.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you want dereferred excecution use Func.

private static Func<Task<string>> GetStringFunc()
    => GetString;

Thus:

var deferred = GetStringFunc();
/*whatever*/
var task = deferred();

Update: please have a look at Lazy<T>.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading