asp.net ashx一般處理程序實現async await異步操作


目前項目存在頁面展示大量圖片,效率不高,考慮優化性能,改為ashx+異步下載的方式,廢話不說直接貼code:

using System;
using System.Web;
using System.IO;
using System.Web.SessionState;
using System.Threading.Tasks;

public class DownLoadS3FileAsync : System.Web.HttpTaskAsyncHandler
{

    public void ProcessRequest(HttpContext context)
    {
        throw new NotImplementedException();
    }

    public override async Task ProcessRequestAsync(HttpContext context)
    {

        SystemError.CreateErrorLog("開始執行異步啦");
        await Task.Run(() =>
        {
            //調用下載方法
            Download(context);
        });
        SystemError.CreateErrorLog("調用異步完成啦");
    }

    public void Download(HttpContext context)
    {
        SystemError.CreateErrorLog("開始下載啦");
        //文件路徑
        string key = context.Request.QueryString["key"];
        byte[] bFile = StorageService.Current.Download(key);


        //輸出
        context.Response.Clear();
        context.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
        context.Response.AddHeader("Content-Length", bFile.Length.ToString());
        context.Response.ContentType = contentType;
        context.Response.OutputStream.Write(bFile, 0, bFile.Length);
        context.Response.Flush();
        context.Response.End();

        SystemError.CreateErrorLog("下載結束了!");
    }
}        

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM