public async Task LockTest() { var asyncLock = new AsyncLock(); var opActive = false; const int time = 200; const int timeInc = 10; const int count = 10; async Task Op(int num) { using (await asyncLock.AcquireAsync()) { Assert.IsFalse(opActive); opActive = true; await TaskEx.Delay(200 + num *timeInc); Assert.IsTrue(opActive); opActive = false; } } var sw = Stopwatch.StartNew(); await Enumerable .Range(0, 10) .Select(i => TaskEx.Run(() => Op(i))) .WhenAll(); sw.Stop(); Assert.IsFalse(opActive); Assert.GreaterOrEqual(sw.ElapsedMilliseconds, time * count + timeInc * count / 2); }
public static void WarningInTaskRun() { if (!Task.Run(() => Assert.Warn("(Warning message)")).Wait(10000)) { Assert.Fail("Timeout while waiting for Task.Run to execute."); } }
/// <summary>开始更新</summary> public void Download() { if (Links.Length == 0) { throw new Exception("没有可用新版本!"); } var link = Links[0]; if (String.IsNullOrEmpty(link.Url)) { throw new Exception("升级包地址无效!"); } // 如果更新包不存在,则下载 var file = UpdatePath.CombinePath(link.Name).GetFullPath(); if (!File.Exists(file)) { WriteLog("准备下载 {0} 到 {1}", link.Url, file); var sw = Stopwatch.StartNew(); var web = CreateClient(); Task.Run(() => web.DownloadFileAsync(link.Url, file)).Wait(); sw.Stop(); WriteLog("下载完成!大小{0:n0}字节,耗时{1:n0}ms", file.AsFile().Length, sw.ElapsedMilliseconds); } SourceFile = file; }
public virtual TValue GetItem(TKey key, Func <TKey, TValue> func) { var exp = Expire; var items = Items; if (items.TryGetValue(key, out var item) && (exp <= 0 || !item.Expired)) { return(item.Value); } // 提前计算,避免因为不同的Key错误锁定了主键 var value = default(TValue); lock (items) { if (items.TryGetValue(key, out item) && (exp <= 0 || !item.Expired)) { return(item.Value); } // 对于缓存命中,仅是缓存过期的项,如果采用异步,则马上修改缓存时间,让后面的来访者直接采用已过期的缓存项 if (exp > 0 && Asynchronous) { if (item != null) { item.ExpiredTime = DateTime.Now.AddSeconds(exp); // 异步更新缓存 if (func != null) { Task.Run(() => { item.Value = func(key); }); } return(item.Value); } } if (func == null) { if (CacheDefault) { items[key] = new CacheItem(value, exp); } } else { value = func(key); if (CacheDefault || !Object.Equals(value, default(TValue))) { items[key] = new CacheItem(value, exp); } } StartTimer(); return(value); } }
/// <summary>检查请求队列是否有匹配该响应的请求</summary> /// <param name="owner">拥有者</param> /// <param name="response">响应的数据</param> /// <param name="remote">远程</param> /// <returns></returns> public virtual Boolean Match(Object owner, Packet response, IPEndPoint remote) { var qs = Items; if (qs.Count == 0) { return(false); } // 加锁复制以后再遍历,避免线程冲突 var arr = qs.ToArray(); foreach (var qi in arr) { if (qi.Owner == owner && (qi.Remote == null || remote == null || qi.Remote + "" == remote + "") && IsMatch(owner, remote, qi.Request, response)) { lock (qs) { qs.Remove(qi); } // 异步设置完成结果,否则可能会在当前线程恢复上层await,导致堵塞当前任务 if (!qi.Source.Task.IsCompleted) { Task.Run(() => qi.Source.SetResult(response)); } return(true); } } if (Setting.Current.Debug) { XTrace.WriteLine("PacketQueue.CheckMatch 失败 [{0}] remote={1} Items={2}", response.Count, remote, arr.Length); } return(false); }
public ActionResult Index() { var list = new List <DbItem>(); var dir = XCode.Setting.Current.BackupPath.AsDirectory(); // 读取配置文件 foreach (var item in DAL.ConnStrs.ToArray()) { var di = new DbItem { Name = item.Key, ConnStr = item.Value }; var dal = DAL.Create(item.Key); di.Type = dal.DbType; var t = Task.Run(() => { try { return(dal.Db.ServerVersion); } catch { return(null); } }); if (t.Wait(300)) { di.Version = t.Result; } if (dir.Exists) { di.Backups = dir.GetFiles("{0}_*".F(dal.ConnName), SearchOption.TopDirectoryOnly).Length; } list.Add(di); } return(View("Index", list)); }
public Task <object> TaskResultCheckSuccessReturningNull() { return(Task.Run(() => (object)null)); }
public async Task <object> AsyncTaskResultCheckSuccessReturningNull() { return(await Task.Run(() => (object)null)); }
public System.Threading.Tasks.Task TaskFailure() { return(Task.Run(() => Assert.AreEqual(1, 2))); }
private static Task <string> GetTestNameFromContext() { return(Task.Run(() => TestContext.CurrentContext.Test.Name)); }
private static Task <int> ThrowException() { Func <int> throws = () => { throw new InvalidOperationException(); }; return(Task.Run(throws)); }
public async System.Threading.Tasks.Task AsyncTaskTestCaseWithExpectedResult() { await Task.Run(() => 1); }
public async Task <int> AsyncGenericTaskTestCase() { return(await Task.Run(() => 1)); }
private async Task <int> Throw() { Func <int> thrower = () => { throw new InvalidOperationException(); }; return(await Task.Run(thrower)); }
public async void AsyncVoidTestCaseWithExpectedResult() { await Task.Run(() => 1); }
public Task <int> GenericTaskTestCaseWithExpectedResult() { return(Task.Run(() => 1)); }
public Task <int> GenericTaskTestCase() { return(Task.Run(() => 1)); }
public System.Threading.Tasks.Task TaskTestCaseWithExpectedResult() { return(Task.Run(() => 1)); }
public async System.Threading.Tasks.Task NestedAsyncTaskFailure() { var result = await Task.Run(async() => await ReturnOne()); Assert.AreEqual(2, result); }
public async Task <int> AsyncGenericTaskTestCaseWithExpectedResult() { return(await Task.Run(() => 1)); }
public async System.Threading.Tasks.Task NestedAsyncTaskError() { await Task.Run(async() => await ThrowException()); Assert.Fail("Should never get here"); }
public static Task Run(Action action) { return(TaskEx.Run(action, CancellationToken.None)); }
private static Task <int> ReturnOne() { return(Task.Run(() => 1)); }
public static Task Run(Func <Task> function, CancellationToken cancellationToken) { return(TaskExtensions.Unwrap(TaskEx.Run <Task>(function, cancellationToken))); }
public System.Threading.Tasks.Task TaskSuccess() { return(Task.Run(() => Assert.AreEqual(1, 1))); }
private static System.Threading.Tasks.Task <int> ReturnOne() { return(Task.Run(() => 1)); }
private static Task<int> One() { return Task.Run(() => 1); }
public static Task <TResult> Run <TResult>(Func <Task <TResult> > function, CancellationToken cancellationToken) { return(TaskExtensions.Unwrap <TResult>(TaskEx.Run <Task <TResult> >(function, cancellationToken))); }
public async Task <T> TestWithAsyncGenericReturnType <T>(T arg1) { return(await Task.Run(() => arg1)); }
public static Task <TResult> Run <TResult>(Func <TResult> function) { return(TaskEx.Run <TResult>(function, CancellationToken.None)); }