-
async await 异步下载 异步代码加锁 lock 异步缓存
async await 异步下载 异步代码加锁 lock 异步缓存
FTP异步下载代码:

/// <summary> /// 异步下载文件 /// </summary> /// <param name="ftpPath">ftp路径</param> /// <param name="ftpUserId">用户名</param> /// <param name="ftpPassword">密码</param> /// <param name="relativeFilePath">文件相对路径</param> public static async Task<MemoryStream> 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 下载 filePath=" + relativeFilePath); return stream; } catch (Exception ex) { request.Abort(); LogUtil.Error(ex); } return null; }
异步缓存代码:

/// <summary> /// 异步获取并缓存数据 /// </summary> /// <param name="cacheKey">键</param> /// <param name="func">在此方法中初始化数据</param> /// <param name="expirationSeconds">缓存过期时间(秒),0表示永不过期</param> /// <param name="refreshCache">立即刷新缓存</param> public static async Task<T> TryGetValueAsync<T>(string cacheKey, Func<Task<T>> func, int expirationSeconds = 0, bool refreshCache = false) { string pre = "CacheHelper.TryGetValueAsync<T>"; 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(); } }
Web API 异步下载接口:

/// <summary> /// 文件下载 /// </summary> /// <param name="filePath">文件存储相对路径</param> [HttpGet] [Route("DownloadFileByPath")] public async Task<HttpResponseMessage> 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 错误:文件不存在"); return new HttpResponseMessage(HttpStatusCode.NotFound); } log.LogTime("CommonController.DownloadFileByPath 下载 filePath=" + filePath); } catch (Exception ex) { LogUtil.Error(ex, "DownloadFileByPath 错误"); return new HttpResponseMessage(HttpStatusCode.NotFound); } return response; }
栏目列表
最新更新
nodejs爬虫
Python正则表达式完全指南
爬取豆瓣Top250图书数据
shp 地图文件批量添加字段
爬虫小试牛刀(爬取学校通知公告)
【python基础】函数-初识函数
【python基础】函数-返回值
HTTP请求:requests模块基础使用必知必会
Python初学者友好丨详解参数传递类型
如何有效管理爬虫流量?
2个场景实例讲解GaussDB(DWS)基表统计信息估
常用的 SQL Server 关键字及其含义
动手分析SQL Server中的事务中使用的锁
openGauss内核分析:SQL by pass & 经典执行
一招教你如何高效批量导入与更新数据
天天写SQL,这些神奇的特性你知道吗?
openGauss内核分析:执行计划生成
[IM002]Navicat ODBC驱动器管理器 未发现数据
初入Sql Server 之 存储过程的简单使用
SQL Server -- 解决存储过程传入参数作为s
关于JS定时器的整理
JS中使用Promise.all控制所有的异步请求都完
js中字符串的方法
import-local执行流程与node模块路径解析流程
检测数据类型的四种方法
js中数组的方法,32种方法
前端操作方法
数据类型
window.localStorage.setItem 和 localStorage.setIte
如何完美解决前端数字计算精度丢失与数