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(); } }