Async await async download asynchronous code lock asynchronous cache

Time:2020-11-27

Async await async download asynchronous code lock asynchronous cache

FTP asynchronous download code:

Async await async download asynchronous code lock asynchronous cacheAsync await async download asynchronous code lock asynchronous cache

/// 
///Download files asynchronously
/// 
///FTP path
///User name
///Password
///File relative path
public static async Task DownloadFileAsync(string ftpPath, string ftpUserId, string ftpPassword, string relativeFilePath)
{
    FtpWebRequest request = null;

    try
    {
        LogTimeUtil log = new LogTimeUtil();
        request = (FtpWebRequest)WebRequest.Create(new Uri(Path.Combine(ftpPath, relativeFilePath).Replace("\\", "/")));
        request.Credentials = new NetworkCredential(ftpUserId, ftpPassword);
        request.Method = "RETR";
        FtpWebResponse response = (FtpWebResponse)(await request.GetResponseAsync());
        Stream responseStream = response.GetResponseStream();
        MemoryStream stream = new MemoryStream();
        byte[] bArr = new byte[1024 * 1024];
        int size = await responseStream.ReadAsync(bArr, 0, (int)bArr.Length);
        while (size > 0)
        {
            stream.Write(bArr, 0, size);
            size = await responseStream.ReadAsync(bArr, 0, (int)bArr.Length);
        }
        stream.Seek(0, SeekOrigin.Begin);
        responseStream.Close();

        log.LogTime (" FtpUtil.DownloadFileAsync  Download filepath = + relativefilepath);
        return stream;
    }
    catch (Exception ex)
    {
        request.Abort();
        LogUtil.Error(ex);
    }

    return null;
}

View Code

Asynchronous cache Code:

Async await async download asynchronous code lock asynchronous cacheAsync await async download asynchronous code lock asynchronous cache

/// 
///Get and cache data asynchronously
/// 
///Key
///Initialize the data in this method
///Never expired (0 seconds), which means the cache will expire
///Refresh cache now
public static async Task TryGetValueAsync(string cacheKey, Func> func, int expirationSeconds = 0, bool refreshCache = false)
{
    string pre = "CacheHelper.TryGetValueAsync";
    SemaphoreSlim sem = _dictSemaphoresForReadCache.GetOrAdd(pre + cacheKey, new SemaphoreSlim(1, 1));
    await sem.WaitAsync();

    try
    {
        object cacheValue = HttpRuntime.Cache.Get(cacheKey);
        if (cacheValue != null)
        {
            return (T)cacheValue;
        }
        else
        {
            T value = await func();
            if (expirationSeconds > 0)
            {
                HttpRuntime.Cache.Insert(cacheKey, value, null, DateTime.Now.AddSeconds(expirationSeconds), Cache.NoSlidingExpiration);
            }
            else
            {
                HttpRuntime.Cache.Insert(cacheKey, value);
            }
            return value;
        }
    }
    catch (Exception ex)
    {
        LogUtil.Error(ex);
        return default(T);
    }
    finally
    {
        sem.Release();
    }
}

View Code

Web API asynchronous Download Interface:

Async await async download asynchronous code lock asynchronous cacheAsync await async download asynchronous code lock asynchronous cache

/// 
///File download
/// 
///File storage relative path
[HttpGet]
[Route("DownloadFileByPath")]
public async Task DownloadFileByPath(string filePath)
{
    HttpResponseMessage response = new HttpResponseMessage();

    try
    {
        LogTimeUtil log = new LogTimeUtil();
        string fileName = Path.GetFileName(filePath);

        if (FtpUtil.FileExists(_ftpPath, _ftpUserId, _ftpPassword, filePath))
        {
            byte[] bArr = await CacheHelper.TryGetValueAsync("DF9165DE189149258B34C405A2A7D7D1" + filePath, async () =>
            {
                MemoryStream ms = await FtpUtil.DownloadFileAsync(_ftpPath, _ftpUserId, _ftpPassword, filePath);
                return ms.ToArray();
            }, 180);

            response.Content = new ByteArrayContent(bArr);
            response.Content.Headers.ContentLength = bArr.Length;
            response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
            response.Content.Headers.ContentDisposition.FileName = fileName;
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        }
        else
        {
            LogUtil.Error ("downloadfilebypath error: file does not exist");
            return new HttpResponseMessage(HttpStatusCode.NotFound);
        }
        log.LogTime (" CommonController.DownloadFileByPath  Download filepath = + filepath);
    }
    catch (Exception ex)
    {
        LogUtil.Error (ex, "downloadfilebypath error");
        return new HttpResponseMessage(HttpStatusCode.NotFound);
    }

    return response;
}

View Code