简体   繁体   English

c# 和 javascript 中的异步有什么区别

[英]What is the difference between asynchrony in c# and in javascript

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?在python和js中,经常会出现阻塞事件循环的问题,当代码在一个线程中执行,同时只能执行一个同步操作,但是我在C#的任何地方都找不到这个问题,也许C#中不存在这个问题,如果不存在,那为什么? And what is the difference between asynchrony in C# and javascript C# 和 javascript 中的异步有什么区别

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# 实际上有多个线程,因此无论何时使用异步编码,它都应该在后台线程上运行,或者使用操作系统提供的异步 IO,因此实际上根本没有线程用于操作。

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. c# UI 程序仍然有一个带有事件循环的 UI 线程,如果您使用不良的编程习惯,死锁是完全可能的。 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.原因是 SomeAsynchronousOperation 可能需要在 UI 线程上运行一些东西才能完成,如果它正在等待任务,这显然是不可能的。

But it is also fairly easy to solve in c#但在 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.通过编译器的魔力,将您的方法重写为 state 机器,消除了死锁的风险。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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