dotnet / docs

This repository contains .NET Documentation.
https://learn.microsoft.com/dotnet
Creative Commons Attribution 4.0 International
4.23k stars 5.87k forks source link

Don't put polling loops into examples! #29010

Closed theREALdebater closed 2 years ago

theREALdebater commented 2 years ago

The second example on this page shows a polling loop:

while(! task1.IsCompleted) {}

In this example it might not be too bad, but in general this kind of loop represents a massive inefficiency. Especially on a modern processor, it could cause a piece of code to execute billions of times more instructions than necessary.

I appreciate your code is only an example, but please don't ever show these polling loops in your examples. Somebody will copy the code, thinking it is safe because it was in an example on MSDN, and cause a lot of trouble, potentially for a lot of people, as a result.

If you have to put a polling loop in an example, please mark it with a big, loud warning that it should never be used in production code. Also, put a delay in the loop, even if it is very small.

Thanks, Nick Roberts


Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

IEvangelist commented 2 years ago

I'm curious what @BillWagner thinks of this?

BillWagner commented 2 years ago

I think we should update that sample. I'd prefer either a Task.Yield(), or a Task.Delay() in the body of that while loop, along with some guidance about when to use each.

@stephentoub should comment on the best recommendations to update the sample, and explain alternatives in the article text.

stephentoub commented 2 years ago

This particular page is showing using a blocking task.Wait, and then it's basically saying if you're not waiting and instead being notified of the completion in some other way, you can access the same exception information via Task.Exception... the polling loop in the subsequent code is just a stand-in for "the task will complete and you'll be notified in some fashion other than task.Wait that it's done". We could add comments to the effect that that's what's going on, we could rip out the whole example, we could keep it as-is, etc. I don't have a strong opinion on it; I think it's ok as-is, FWIW.