Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Analyzer proposal: Use Task.Delay instead of Thread.Sleep in an async method #754

Closed
nbarbettini opened this issue Feb 3, 2021 · 7 comments

Comments

@nbarbettini
Copy link

Using Thread.Sleep() inside an async method is a bad idea. await Task.Delay() is a drop-in replacement. It would be great to have an analyzer rule (and an accompanying code fix) to catch accidental use of Thread.Sleep.

Back on the old AsyncUsageAnalyzers repo, there was this discussion: DotNetAnalyzers/AsyncUsageAnalyzers#2
And also a related PR: DotNetAnalyzers/AsyncUsageAnalyzers#50

Is vs-threading the right place for an analyzer like this?

@AArnott
Copy link
Member

AArnott commented Feb 5, 2021

Thread.Sleep is almost always a bad idea. If it appeared in a sync method, the diagnostic might even appear suggesting the method be made async.
I like the idea, and traditionally this would be a great repo for it. However the .NET team is in the process of migrating analyzers of general interest from this repo to theirs. So we should reach out to them to gauge interest before starting work here.

@nbarbettini
Copy link
Author

Makes sense. Does reaching out mean cross-posting to a different repo, or something else?

@AArnott
Copy link
Member

AArnott commented Feb 18, 2021

Yes. But I can't remember which dotnet repo keeps the new analyzers.

@davkean
Copy link
Member

davkean commented Apr 1, 2022

They are filling them directly in the runtime repository, here's an example: dotnet/runtime#67123.

//cc @terrajobst

@davkean davkean closed this as completed Apr 1, 2022
@snjjay
Copy link

snjjay commented Jun 11, 2022

Task. Sleep is a synchronous thread that puts the thread to sleep so it can't be used for anything else. Task, on the other hand. Delay is an asynchronous thread that can be used to perform other tasks while it waits. Refer to this https://kodlogs.net/1/task-delay-vs-thread-sleep

@AArnott
Copy link
Member

AArnott commented Jun 12, 2022

@snjjay: I think instead of "Task. Sleep" you meant "Thread.Sleep".
Task.Delay is not any thread at all. It's an OS kernel timer that sends a message that the runtime translates into a thread pool work item.

It's not clear to me what point you were trying to make with your comment. I think everyone here understands the difference between the two methods.

@Mihirpatel2005

This comment was marked as spam.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

5 participants