.net 4.5中异步和同步之间的区别 [英] difference between Asynchronous and Synchronous in .net 4.5

查看:300
本文介绍了.net 4.5中异步和同步之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读有关.Net 4.5中的异步编程的内容时, async await 关键字
我读了< a href = http://www.asp.net/mvc/overview/performance/using-asynchronous-methods-in-aspnet-mvc-4 rel = noreferrer>此处以下段落 p>


处理异步请求



在看到大量并发请求的Web应用程序中
的启动或负载突增(并发性突然增加),
使这些Web服务调用异步将增加应用程序的
响应速度。 异步请求所花费的时间
与同步请求所花费的时间相同。以
为例,如果一个请求进行的Web服务调用需要两个
秒才能完成,那么无论是同步执行还是异步执行
,该请求都将花费两秒钟
。但是,在
异步调用期间,在等待第一个请求完成时,不会阻止线程响应其他
请求。因此,当有许多并发请求调用长时间运行的
操作时,
异步请求会阻止请求排队和线程池增长。

对于粗体字,我无法理解,异步请求如何处理与同步请求相同的时间?



例如:

 公共异步任务MyMethod()
{
Task< int> longRunningTask = LongRunningOperation();
//确实可以独立于int结果工作在这里

//现在我们在任务上调用await
int result = await longRunningTask;
//使用结果
Console.WriteLine(result);
}

公共异步任务< int> LongRunningOperation()//假设我们从这个长时间运行的操作中返回一个int
{
await Task.Delay(1000); // 1秒延迟
返回1;
}

我了解到 LongRunningOperation()从第一行开始执行,在这里调用 Task< int> longRunningTask = LongRunningOperation(); 并在调用 await
后返回值,所以从我的角度来看,异步代码比同步代码快,



另一个问题:



我了解主线程正在执行 MyMethod()未被阻止等待 LongRunningOperation()完成,但它返回线程池以服务另一个请求。那么是否有另一个线程分配给 LongRunningOperation(); 来执行它?



如果是那么异步编程和多线程编程之间有什么区别?



更新:



让我们说代码变成了这样:

 公共异步任务MyMethod()
{
任务< int> longRunningTask = LongRunningOperation();
//确实可以独立于int结果工作在这里
DoIndependentWork();
//现在我们在任务
上调用await int result = await longRunningTask;
//使用结果
Console.WriteLine(result);
}

公共异步任务< int> LongRunningOperation()//假设我们从这个长期运行的操作中返回一个int
{
DoSomeWorkNeedsExecution();
等待Task.Delay(1000); // 1秒延迟
返回1;
}

在这种情况下,将 LongRunningOperation() DoIndependentWork()执行期间的另一个线程执行?

解决方案

异步操作并不快。如果异步(即 await Task.Delay(10000))或同步(即 Thread.Sleep(10000)将花费相同的10秒。唯一的不同是第一个在等待时不会占用线程,而第二个会



现在,如果您启动一个任务,不要等待它立即完成,您可以使用同一线程来执行其他一些工作,但是它不会加快异步操作的运行速度:

  var task = Task.Delay(10000); 
//处理
等待任务; //仅在10秒后完成

关于第二个问题:任务。延迟(就像其他真正的异步操作一样)不需要执行线程,因此没有线程 Task.Delay 使用您启动的 System.Threading.Timer 实现,并在完成后引发事件,与此同时,它不需要线程,因为没有代码可以执行。



因此,当运行 MyMethod 到达 await longRunningTask 便被释放(只要 longRunningTask 尚未完成)。如果它是 ThreadPool 线程,它将返回到 ThreadPool ,在这里它可以处理应用程序中的其他代码。 / p>




关于更新,流程如下:




  • MyMethod 开始处理

  • LongRunningOperation 开始处理

  • DoSomeWorkNeedsExecution 在调用线程上执行

  • An await LongRunningOperation 中到达,因此返回了一个热门任务。

  • DoIndependentWork 由同一调用线程执行( LongRunningOperation 仍在运行,不需要线程)

  • MyMethod 中达到了等待。如果原始任务完成,则同一线程将同步进行,否则将返回最终完成的热任务。



因此,您使用 async-await 的事实使您可以使用一个线程,否则该线程将被阻塞,等待与CPU密集型工作同步执行。


During my reading about Asynchronous Programming in .Net 4.5 async and await keywords I read Here the following paragraph

Processing Asynchronous Requests

In web applications that sees a large number of concurrent requests at start-up or has a bursty load (where concurrency increases suddenly), making these web service calls asynchronous will increase the responsiveness of your application. An asynchronous request takes the same amount of time to process as a synchronous request. For example, if a request makes a web service call that requires two seconds to complete, the request takes two seconds whether it is performed synchronously or asynchronously. However, during an asynchronous call, a thread is not blocked from responding to other requests while it waits for the first request to complete. Therefore, asynchronous requests prevent request queuing and thread pool growth when there are many concurrent requests that invoke long-running operations.

for the bold words, I couldn't understand them how An asynchronous request takes the same amount of time to process as a synchronous request?

For example:

public async Task MyMethod()
{
    Task<int> longRunningTask = LongRunningOperation();
    //indeed you can do independent to the int result work here 

    //and now we call await on the task 
    int result = await longRunningTask;
    //use the result 
    Console.WriteLine(result);
}

public async Task<int> LongRunningOperation() // assume we return an int from this long running operation 
{
    await Task.Delay(1000); //1 seconds delay
    return 1;
}

What I understand that LongRunningOperation() starts execution from the first line calling here Task<int> longRunningTask = LongRunningOperation(); and returns value once calling await, so from my point of view asynchronous code faster than synchronous, is that right?

Another question:

What I understand that the main thread working on executing MyMethod() not blocked waiting for LongRunningOperation() to be accomplished but it returns to thread pool to serve another request. so is there another thread assigned to LongRunningOperation(); to execute it?

If yes so what is the difference between Asynchronous Programming and Multithreading Programming ?

Update:

let's say that code becomes like that:

public async Task MyMethod()
    {
        Task<int> longRunningTask = LongRunningOperation();
        //indeed you can do independent to the int result work here 
        DoIndependentWork();
        //and now we call await on the task 
        int result = await longRunningTask;
        //use the result 
        Console.WriteLine(result);
    }

    public async Task<int> LongRunningOperation() // assume we return an int from this long running operation 
    {
        DoSomeWorkNeedsExecution();
        await Task.Delay(1000); //1 seconds delay
        return 1;
    }

In this case , will LongRunningOperation() be executed by another thread during DoIndependentWork() execution?

解决方案

The asynchronous operations aren't faster. If you wait for 10 seconds asynchronously (i.e. await Task.Delay(10000)) or synchronously (i.e. Thread.Sleep(10000)) it would take the same 10 seconds. The only difference would be that the first would not hold up a thread while waiting but the second will.

Now, if you fire up a task and don't wait for it to complete immediately you can use the same thread to do some other work, but it doesn't "speed up" the asynchronous operation's run:

var task = Task.Delay(10000);
// processing
await task; // will complete only after 10 seconds

About your second question: Task.Delay (like other truly asynchronous operations) doesn't need a thread to be executed and so there is no thread. Task.Delay is implemented using a System.Threading.Timer that you fire up and it raises an event when it's done, in the meantime it doesn't need a thread because there's no code to execute.

So when the thread that was running MyMethod reaches the await longRunningTask it is freed (as long as longRunningTask hasn't completed yet). If it was a ThreadPool thread it will return to the ThreadPool where it can process some other code in your application.


Regarding the update the flow would be so:

  • MyMethod starts processing
  • LongRunningOperation starts processing
  • DoSomeWorkNeedsExecution is executed on the calling thread
  • An await is reached in LongRunningOperation and so a hot task is returned.
  • DoIndependentWork is executed by the same calling thread (LongRunningOperation is still "running", no thread is needed)
  • An await is reached in MyMethod. If the original task completed the same thread will proceed on synchronously, if not then a hot task would be returned that would complete eventually.

So the fact that you're using async-await allows you to use a thread that would otherwise be blocked waiting synchronously to executed CPU-intensive work.

这篇关于.net 4.5中异步和同步之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆