Create a completed Task

When targeting .NET 4.5 you can use Task.FromResult: public static Task<TResult> FromResult<TResult>(TResult result); To create a failed task, use Task.FromException: public static Task FromException(Exception exception); public static Task<TResult> FromException<TResult>(Exception exception); .NET 4.6 adds Task.CompletedTask if you need a non generic Task. public static Task CompletedTask { get; } Workarounds for older versions of .NET: When … Read more

What’s the difference between returning void and returning a Task?

SLaks and Killercam’s answers are good; I thought I’d just add a bit more context. Your first question is essentially about what methods can be marked async. A method marked as async can return void, Task or Task<T>. What are the differences between them? A Task<T> returning async method can be awaited, and when the … Read more

Default parameter for CancellationToken

It turns out that the following works: Task<x> DoStuff(…., CancellationToken ct = default(CancellationToken)) …or: Task<x> DoStuff(…., CancellationToken ct = default) // C# 7.1 and later which, according to the documentation, is interpreted the same as CancellationToken.None: You can also use the C# default(CancellationToken) statement to create an empty cancellation token.

Difference between await and ContinueWith

Here’s the sequence of code snippets I recently used to illustrate the difference and various problems using async solves. Suppose you have some event handler in your GUI-based application that takes a lot of time, and so you’d like to make it asynchronous. Here’s the synchronous logic you start with: while (true) { string result … Read more

Why CancellationToken is separate from CancellationTokenSource?

I was involved in the design and implementation of these classes. The short answer is “separation of concerns“. It is quite true that there are various implementation strategies and that some are simpler at least regarding the type system and initial learning. However, CTS and CT are intended for use in a great many scenarios … Read more

Why should I prefer single ‘await Task.WhenAll’ over multiple awaits?

Yes, use WhenAll because it propagates all errors at once. With the multiple awaits, you lose errors if one of the earlier awaits throws. Another important difference is that WhenAll will wait for all tasks to complete even in the presence of failures (faulted or canceled tasks). Awaiting manually in sequence would cause unexpected concurrency … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)