异步和/或在其自己的线程上调用方法以提高性能 [英] Invoking a method asynchronously and/or on its own thread to increase performance

查看:68
本文介绍了异步和/或在其自己的线程上调用方法以提高性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题涉及我使用asp.net/c#创建的Web api,并将其部署到Azure服务器.该API基本上会收到处理图像的请求,该图像上印有一些文本.

My question is involving a web api I created using asp.net/c# and is deployed to an Azure server. The API basically gets a requests to process an image with some text printed over it.

我有一个一旦接收到get请求即被调用的方法.用英语来说,该方法进行了一些设置,然后从Azure blob存储下载所需的正确图像,然后进行绘制.

I have a method that is called once a get request is received. In english, the method does some setup, then downloads the proper image requested from Azure blob storage, then does the drawing.

public HttpResponseMessage process(string image){

DoSomeSetup();  

DownloadFromBlob(image);

return DrawTextOnImage();
}

我的问题是,从Azure blob下载花费了所有操作中最长的时间,通常是2-3秒.我认为,如果可以在安装过程中下载图像以节省时间,则效率会更高.

My problem is that downloading from the Azure blob takes the longest time out of all the operations, usually 2-3 seconds. I figure that it would be much more efficient if I could download the image WHILE setup is occurring, in order to save time.

public HttpResponseMessage process(string image){

startDownloadingImageFromBlob(image);

DoSomeSetup();

EnsureImageDownloadFinished();

return DrawTextOnImage();
}

给我的印象是,只需致电

I am under the impression that simply calling

Bitmap templateImage = DownloadImageFromUrl(BLOB_STORAGE_TEMPLATES_BASE_URL)

方法顶部的

将等待下载完成,然后再进入设置.有没有一种方法可以让我在安装过程中同时进行下载,然后(如果需要)在完成绘制之前等待它完成?

at the top of the method will wait for the download to complete before moving onto the setup. Is there a way that I can get the download to happen at the same time as setup, and then (if necessary) wait for it to finish before drawing?

推荐答案

您不应在ASP.NET上使用WaitTask.Run.

You should not use Wait or Task.Run on ASP.NET.

由于下载是基于I/O的操作,因此异步方法最有意义. 首先要做的事情是确定DownloadFromBlob正在调用哪些API,将它们更改为它们的异步等效项,然后使用await进行调用.然后允许async从那里开始(编译器将指导您).最终,您将得到如下结果:

Since a download is an I/O-based operation, an asynchronous approach makes the most sense. The first thing to do is identify which APIs are being called by DownloadFromBlob, change them to their asynchronous equivalents, and call them using await. Then allow async to grow from there (the compiler will guide you). Eventually, you'll end up with something like:

async Task<Bitmap> DownloadFromBlobAsync(string image);

此时,您可以通过调用(但不是 await)方法,然后在设置完成后await的任务来开始下载:

And at this point, you can start the download by invoking (but not awaiting) the method, and then await the task after your setup is done:

public async Task<HttpResponseMessage> process(string image)
{
  var task = DownloadFromBlobAsync(image);
  var setupData = DoSomeSetup();
  var image = await task;
  return DrawTextOnImage(image, setupData);
}

这篇关于异步和/或在其自己的线程上调用方法以提高性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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