Ejemplo n.º 1
0
        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);
        }
Ejemplo n.º 2
0
 public static void WarningInTaskRun()
 {
     if (!Task.Run(() => Assert.Warn("(Warning message)")).Wait(10000))
     {
         Assert.Fail("Timeout while waiting for Task.Run to execute.");
     }
 }
Ejemplo n.º 3
0
        /// <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;
        }
Ejemplo n.º 4
0
        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);
            }
        }
Ejemplo n.º 5
0
        /// <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);
        }
Ejemplo n.º 6
0
        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));
        }
Ejemplo n.º 7
0
 public Task <object> TaskResultCheckSuccessReturningNull()
 {
     return(Task.Run(() => (object)null));
 }
Ejemplo n.º 8
0
 public async Task <object> AsyncTaskResultCheckSuccessReturningNull()
 {
     return(await Task.Run(() => (object)null));
 }
Ejemplo n.º 9
0
 public System.Threading.Tasks.Task TaskFailure()
 {
     return(Task.Run(() => Assert.AreEqual(1, 2)));
 }
Ejemplo n.º 10
0
 private static Task <string> GetTestNameFromContext()
 {
     return(Task.Run(() => TestContext.CurrentContext.Test.Name));
 }
Ejemplo n.º 11
0
        private static Task <int> ThrowException()
        {
            Func <int> throws = () => { throw new InvalidOperationException(); };

            return(Task.Run(throws));
        }
Ejemplo n.º 12
0
 public async System.Threading.Tasks.Task AsyncTaskTestCaseWithExpectedResult()
 {
     await Task.Run(() => 1);
 }
Ejemplo n.º 13
0
 public async Task <int> AsyncGenericTaskTestCase()
 {
     return(await Task.Run(() => 1));
 }
Ejemplo n.º 14
0
        private async Task <int> Throw()
        {
            Func <int> thrower = () => { throw new InvalidOperationException(); };

            return(await Task.Run(thrower));
        }
Ejemplo n.º 15
0
 public async void AsyncVoidTestCaseWithExpectedResult()
 {
     await Task.Run(() => 1);
 }
Ejemplo n.º 16
0
 public Task <int> GenericTaskTestCaseWithExpectedResult()
 {
     return(Task.Run(() => 1));
 }
Ejemplo n.º 17
0
 public Task <int> GenericTaskTestCase()
 {
     return(Task.Run(() => 1));
 }
Ejemplo n.º 18
0
 public System.Threading.Tasks.Task TaskTestCaseWithExpectedResult()
 {
     return(Task.Run(() => 1));
 }
Ejemplo n.º 19
0
        public async System.Threading.Tasks.Task NestedAsyncTaskFailure()
        {
            var result = await Task.Run(async() => await ReturnOne());

            Assert.AreEqual(2, result);
        }
Ejemplo n.º 20
0
 public async Task <int> AsyncGenericTaskTestCaseWithExpectedResult()
 {
     return(await Task.Run(() => 1));
 }
Ejemplo n.º 21
0
        public async System.Threading.Tasks.Task NestedAsyncTaskError()
        {
            await Task.Run(async() => await ThrowException());

            Assert.Fail("Should never get here");
        }
Ejemplo n.º 22
0
 public static Task Run(Action action)
 {
     return(TaskEx.Run(action, CancellationToken.None));
 }
Ejemplo n.º 23
0
 private static Task <int> ReturnOne()
 {
     return(Task.Run(() => 1));
 }
Ejemplo n.º 24
0
 public static Task Run(Func <Task> function, CancellationToken cancellationToken)
 {
     return(TaskExtensions.Unwrap(TaskEx.Run <Task>(function, cancellationToken)));
 }
Ejemplo n.º 25
0
 public System.Threading.Tasks.Task TaskSuccess()
 {
     return(Task.Run(() => Assert.AreEqual(1, 1)));
 }
Ejemplo n.º 26
0
 private static System.Threading.Tasks.Task <int> ReturnOne()
 {
     return(Task.Run(() => 1));
 }
Ejemplo n.º 27
0
 private static Task<int> One()
 {
     return Task.Run(() => 1);
 }
Ejemplo n.º 28
0
 public static Task <TResult> Run <TResult>(Func <Task <TResult> > function, CancellationToken cancellationToken)
 {
     return(TaskExtensions.Unwrap <TResult>(TaskEx.Run <Task <TResult> >(function, cancellationToken)));
 }
Ejemplo n.º 29
0
 public async Task <T> TestWithAsyncGenericReturnType <T>(T arg1)
 {
     return(await Task.Run(() => arg1));
 }
Ejemplo n.º 30
0
 public static Task <TResult> Run <TResult>(Func <TResult> function)
 {
     return(TaskEx.Run <TResult>(function, CancellationToken.None));
 }