public static async Task <Result <K, E> > Combine <T, K, E>(this Task <IEnumerable <Task <Result <T, E> > > > task, Func <IEnumerable <T>, K> composer)
            where E : ICombine
        {
            IEnumerable <Task <Result <T, E> > > tasks = await task.ConfigureAwait(Result.DefaultConfigureAwait);

            return(await tasks.Combine(composer).ConfigureAwait(Result.DefaultConfigureAwait));
        }
        public static async Task <Result <IEnumerable <T>, E> > Combine <T, E>(this IEnumerable <Task <Result <T, E> > > tasks)
            where E : ICombine
        {
            Result <T, E>[] results = await Task.WhenAll(tasks).ConfigureAwait(Result.DefaultConfigureAwait);

            return(results.Combine());
        }
        public static async Task <Result <K, E> > Combine <T, K, E>(this IEnumerable <Task <Result <T, E> > > tasks, Func <IEnumerable <T>, K> composer)
            where E : ICombine
        {
            IEnumerable <Result <T, E> > results = await Task.WhenAll(tasks).ConfigureAwait(Result.DefaultConfigureAwait);

            return(results.Combine(composer));
        }
        public static async Task <Result <K, E> > CombineInOrder <T, K, E>(this Task <IEnumerable <Task <Result <T, E> > > > task, Func <IEnumerable <T>, K> composer)
            where E : ICombine
        {
            IEnumerable <Task <Result <T, E> > > tasks = await task.DefaultAwait();

            return(await tasks.CombineInOrder(composer).DefaultAwait());
        }
Example #5
0
        public static async Task <Result <IEnumerable <T>, E> > Combine <T, E>(this Task <IEnumerable <Result <T, E> > > task)
            where E : ICombine
        {
            IEnumerable <Result <T, E> > results = await task.DefaultAwait();

            return(results.Combine());
        }
        public static async Task <Result <IEnumerable <T>, E> > Combine <T, E>(this Task <IEnumerable <Task <Result <T, E> > > > task)
            where E : ICombine
        {
            IEnumerable <Task <Result <T, E> > > tasks = await task.ConfigureAwait(Result.DefaultConfigureAwait);

            return(await tasks.Combine().ConfigureAwait(Result.DefaultConfigureAwait));
        }
Example #7
0
 public static void WarningInTaskRun()
 {
     if (!Task.Run(() => Assert.Warn("(Warning message)")).Wait(10000))
     {
         Assert.Fail("Timeout while waiting for Task.Run to execute.");
     }
 }
Example #8
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;
        }
Example #9
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);
        }
Example #10
0
 public void AsyncThrownOperationCanceledExceptionShouldNotChangeType()
 {
     Assert.That(async() =>
     {
         await Task.Yield();
         throw new OperationCanceledException();
     }, Throws.TypeOf <OperationCanceledException>());
 }
Example #11
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);
            }
        }
 public void TwoAsserts_BothAssertsFail_Async()
 {
     Assert.Multiple(async() =>
     {
         await Task.Delay(100);
         Assert.That(complex.RealPart, Is.EqualTo(5.0), "RealPart");
         Assert.That(complex.ImaginaryPart, Is.EqualTo(4.2), "ImaginaryPart");
     });
 }
 public void ThreeAssertsSucceed_Async()
 {
     Assert.Multiple(async() =>
     {
         await Task.Delay(100);
         Assert.That(2 + 2, Is.EqualTo(4));
         Assert.That(complex.RealPart, Is.EqualTo(5.2));
         Assert.That(complex.ImaginaryPart, Is.EqualTo(3.9));
     });
 }
 public static Task <Result <T, E> > CheckIf <T, K, E>(this Result <T, E> result, Func <T, bool> predicate, Func <T, Task <Result <K, E> > > func)
 {
     if (result.IsSuccess && predicate(result.Value))
     {
         return(result.Check(func));
     }
     else
     {
         return(Task.FromResult(result));
     }
 }
 public static Task <Result <T, E> > CheckIf <T, K, E>(this Result <T, E> result, bool condition, Func <T, Task <Result <K, E> > > func)
 {
     if (condition)
     {
         return(result.Check(func));
     }
     else
     {
         return(Task.FromResult(result));
     }
 }
Example #16
0
        static TaskUtils()
        {
            var src = new TaskCompletionSource <Object>();

            src.SetResult(null);

            CompletedTask = src.Task;

            True  = TTaskExt.FromResult(true);
            False = TTaskExt.FromResult(false);
        }
Example #17
0
        /// <summary>
        /// Executes a provided <see cref="Task"/>, cancelling the task and executing a fallback action if the Task doesn't complete before the provided timeout.
        /// </summary>
        /// <param name="ct"></param>
        /// <param name="taskSelector"></param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        public static async Task Timeout(CancellationToken ct, Func <CancellationToken, Task> taskSelector, TimeSpan timeout, Action onTimedOut)
        {
            // We're not using CancellationTokenSource's timeout support because we want to be able to trace code and know when it's
            // about to be cancelled because of a timeout.
            using (var tokenSource = new CancellationTokenSource())
            {
                var task = taskSelector(tokenSource.Token);

                if ((await StaticTask.WhenAny(task, StaticTask.Delay(timeout, ct))) != task)
                {
                    // We timed out, cancel the task and throw a relevant exception.
                    tokenSource.Cancel();
                    onTimedOut();
                }
            }
        }
        public void TwoNestedBlocks_TwoAssertsFail_Async()
        {
            Assert.Multiple(() =>
            {
                Assert.Multiple(async() =>
                {
                    await Task.Delay(100);
                    Assert.That(2 + 2, Is.EqualTo(5));
                });

                Assert.Multiple(async() =>
                {
                    await Task.Delay(100);
                    Assert.That(complex.RealPart, Is.EqualTo(5.2), "RealPart");
                    Assert.That(complex.ImaginaryPart, Is.EqualTo(4.2), "ImaginaryPart");
                });
            });
        }
Example #19
0
 private static async Task <bool> TryTakeAndHold(
     [NotNull] AsyncLock asyncLock, TimeSpan holdTime, CancellationToken cancellation = default(CancellationToken), Action callback = null)
 {
     try
     {
         using (await asyncLock.AcquireAsync(holdTime, cancellation))
         {
             callback?.Invoke();
             await TaskEx.Delay(holdTime);
         }
         return(true);
     }
     catch (OperationCanceledException)
     {
         return(false);
     }
     catch (TimeoutException)
     {
         return(false);
     }
 }
Example #20
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);
        }
Example #21
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));
        }
Example #22
0
        public async Task LockCancellationTest()
        {
            var asyncLock = new AsyncLock();
            var holdTime  = TimeSpan.FromSeconds(2);
            var delayTime = TimeSpan.FromMilliseconds(200);

            var lock1Started = new ManualResetEventSlim(false);

            var lock1 = TryTakeAndHold(asyncLock, holdTime, callback: () => lock1Started.Set());

            lock1Started.Wait();

            var cts2  = new CancellationTokenSource();
            var sw2   = Stopwatch.StartNew();
            var lock2 = TryTakeAndHold(asyncLock, holdTime, cts2.Token);
            await TaskEx.Delay(delayTime);

            cts2.Cancel();
            var lock2Taken = await lock2;

            sw2.Stop();

            var sw3   = Stopwatch.StartNew();
            var lock3 = TryTakeAndHold(asyncLock, delayTime);
            await TaskEx.Delay(delayTime);

            var lock3Taken = await lock3;

            sw3.Stop();

            var lock1Taken = await lock1;

            Assert.IsTrue(lock1Taken);
            Assert.IsFalse(lock2Taken);
            Assert.Less(sw2.Elapsed, holdTime - delayTime);
            Assert.IsFalse(lock3Taken);
            Assert.Less(sw3.Elapsed, holdTime - delayTime);
        }
Example #23
0
 public async Task <T> TestWithAsyncGenericReturnType <T>(T arg1)
 {
     return(await Task.Run(() => arg1));
 }
Example #24
0
 private static Task<int> One()
 {
     return Task.Run(() => 1);
 }
Example #25
0
        public async System.Threading.Tasks.Task NestedAsyncTaskError()
        {
            await Task.Run(async() => await ThrowException());

            Assert.Fail("Should never get here");
        }
Example #26
0
 public System.Threading.Tasks.Task TaskFailure()
 {
     return(Task.Run(() => Assert.AreEqual(1, 2)));
 }
Example #27
0
 public System.Threading.Tasks.Task TaskSuccess()
 {
     return(Task.Run(() => Assert.AreEqual(1, 1)));
 }
Example #28
0
        private static Task <int> ThrowException()
        {
            Func <int> throws = () => { throw new InvalidOperationException(); };

            return(Task.Run(throws));
        }
Example #29
0
 private static Task <int> ReturnOne()
 {
     return(Task.Run(() => 1));
 }
Example #30
0
 private static Task <string> GetTestNameFromContext()
 {
     return(Task.Run(() => TestContext.CurrentContext.Test.Name));
 }