简体   繁体   中英

What generic type argument to use for TaskCompletionSource if no result is actually needed

If we want to create a TaskCompletionSource<T> based Task that has no Result we still need to provide a T and set a dummy value. Like this:

Task SomethingAsync() {
 var tcs = new TaskCompletionSource<?>();
 tcs.SetResult(default(?)); //Can happen later as well, this is for demo purposes.
 return tcs.Task;
}

What's the best type to use for T from a performance standpoint?

It seems hard to answer that question purely from running a micro benchmark. I imagine the answer depends on the rest of the application. For example, if we use TaskCompletionSource<bool> that will cause the JIT to generate specialized code and cause memory usage. But it will not add memory usage if the app already uses boolean based tasks. If we use TaskCompletionSource<object> we might use more memory for each task (or not depending on the runtime).

That's why I think a benchmark alone cannot answer the question and it must be answered by reasoning as well.

If you really want the best possible solution, you need to declare an empty struct. This way, the system won't have to reserve any space for the payload. This is actually what is done in the base class library:

https://referencesource.microsoft.com/#System.Core/System/Threading/Tasks/TaskExtensions.cs,6e36a68760fb02e6,references

private struct VoidResult { }

From there, you can use TaskCompletionSource<VoidResult> , and TrySetResult(default(VoidResult)) to mark the task as completed.

That said, it saves a tiny bit of memory, but I don't think it has any impact on execution time (even at nanoseconds level). Whether you use a TaskCompletionSource<byte> (one byte reserved for the payload) or TaskCompletionSource<object> (four bytes reserved for the payload), a 32 bit CPU is still able to do the assignment in a single operation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM