Exemplo n.º 1
0
        public static async Task Run()
        {
#if DEBUG
            // 使用TaskLogger会影响内存和性能,所以仅在调试生成中启用
            TaskLogger.LogLevel = TaskLogger.TaskLogLevel.Pending;
#endif

            var cts = new CancellationTokenSource(3000);

            var tasks = new List <Task>()
            {
                Task.Delay(2000, cts.Token).Log("2s op"),
                Task.Delay(5000, cts.Token).Log("5s op"),
                Task.Delay(6000, cts.Token).Log("6s op"),
            };

            try
            {
                await Task.WhenAll(tasks);
            }
            catch (OperationCanceledException e)
            {
                Console.WriteLine(e);
            }

            foreach (var entry in TaskLogger.GetLogEntries().OrderBy(u => u.LogTime))
            {
                Console.WriteLine(entry.ToString());
            }
        }
Exemplo n.º 2
0
    public static async Task Go()
    {
        //A async method, so you can invoke wait method.
#if DEBUG
        // Using TaskLogger incurs a memory and performance hit; so turn it on in debug builds
        TaskLogger.LogLevel = TaskLogger.TaskLogLevel.Pending;
#endif

        // Initiate 3 task; for testing the TaskLogger, we control their duration explicitly
        var tasks = new List <Task> {
            Task.Delay(2000).Log("2s op"),
            Task.Delay(5000).Log("5s op"),
            Task.Delay(6000).Log("6s op")
        };

        try {
            // Wait for all tasks but cancel after 3 seconds; only 1 task above should complete in time
            // CancellationTokenSource have three constructors, one of is Int32 means that
            // a millionsecondDely, another one is TimeSpan.
            await Task.WhenAll(tasks).
            WithCancellation(new CancellationTokenSource(3000).Token); // Extension method with new argument is passed.
        }
        catch (OperationCanceledException) { }

        // Ask the logger which tasks have not yet completed and sort
        // them in order from the one that’s been waiting the longest
        foreach (var op in TaskLogger.GetLogEntries().OrderBy(tle => tle.LogTime))
        {
            Console.WriteLine(op);
        }
    }