简体   繁体   English

该程序会被视为异步程序吗?

[英]Would this program be considered asynchronous?

Let's say I have a simple program like 假设我有一个简单的程序,例如

public static main(string[] args)
{
    Task<int> hotTask = Task<int>.Run(() => SomethingThatRunsInBackgroundAndReturnsAnInt());
    DoIndependentWork();
    hotTask.Wait(); 
    Console.WriteLine(hotTask.Result);
}

Would this technically be "synchronous" despite the fact that it runs a background thread that doesn't need to be finished before the next unit of work ( DoIndependentWork() ) is started and finished? 尽管它运行不需要在下一个工作单元( DoIndependentWork() )开始和完成之前完成的后台线程, DoIndependentWork()技术上讲,这在技术上是“同步的”吗? I can't find a very good technical definition anywhere on the internet. 我在互联网上的任何地方都找不到很好的技术定义。

According to this : Asynchronous vs synchronous execution, what does it really mean? 据此: 异步与同步执行的真正含义是什么?

When you execute something synchronously, you wait for it to finish before moving on to another task. 当您同步执行某项任务时,您需要等待其完成才能继续执行其他任务。 When you execute something asynchronously, you can move on to another task before it finishes. 当您异步执行某些操作时,您可以在完成任务之前继续执行其他任务。

In your case you do SomethingThatRunsInBackgroundAndReturnsAnInt() and you do not wait for the task to end, but rather execute another function, which means that it is an asynchronous program 在您的情况下,您执行SomethingThatRunsInBackgroundAndReturnsAnInt()而不必等待任务结束,而是执行另一个函数,这意味着它是一个异步程序

Yeah, sort of, but technically, no 是的,但从技术上讲,不是

Maybe this is a nit, but I would state that your program uses asynchronous operations, but is not itself asynchronous. 也许这是一个小问题,但我要指出您的程序使用异步操作,但本身不是异步的。 This is because the program's main method will not return until the program has finished processing. 这是因为在程序完成处理之前,程序的main方法将不会返回。

When we talk about an asynchronous method, we are not talking about a method that uses multiple threads; 当我们谈论异步方法时,我们并不是在谈论使用多个线程的方法。 we are talking about a method that returns nearly immediately and before the work is done. 我们正在谈论一种几乎在工作完成之前立即返回的方法。 Similarly, for a program, we are not talking about a program that uses multiple threads, but a program that returns nearly immediately and before the work is done. 同样,对于一个程序,我们不是在谈论使用多个线程的程序,而是要在工作完成之前立即返回的程序。

An example of an asynchronous program would be a Windows Service . Windows Service是异步程序的一个示例。 The operating system will call the service's OnStart method, which returns nearly immediately. 操作系统将调用服务的OnStart方法,该方法几乎立即返回。 Meanwhile the service maintains another thread which does the main work asynchronously. 同时,服务维护另一个异步执行主要工作的线程。

Your program, therefore, does not meet the definition. 因此,您的程序不符合定义。

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

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