-1

In python and js, there is often a problem associated with blocking the event loop, when the code is executed in one thread and only one synchronous operation can be performed at the same time, but I could not find this problem anywhere in C#, maybe this problem does not exist in C#, if not, then why? And what is the difference between asynchrony in C# and javascript

RomanGodMode
  • 325
  • 3
  • 11

1 Answers1

0

c# actually has multiple threads, so whenever asynchronous coding is used it should either run on a background thread, or use asynchronous IO provided by the OS, so no thread is actually used at all for the operation.

c# UI programs still have a UI thread with an event loop, and it is perfectly possible to deadlock if you use poor programming practices. As an example:

Task task = SomeAsynchronousOperation();
task.Wait(); // can deadlock if run on the UI thread

The reason is that SomeAsynchronousOperation might need to run something on the UI thread to complete, and this is obviously not possible if it is waiting a task.

But it is also fairly easy to solve in c#

Task task = SomeAsynchronousOperation();
await task; // No deadlock

By the magic of the compiler rewriting your method into a state machine the risk of deadlock is removed.

JonasH
  • 28,608
  • 2
  • 10
  • 23