相关疑难解决方法(0)

关于Task.Start(),Task.Run()和Task.Factory.StartNew()的使用

我刚看到3个关于TPL使用的例程,它们执行相同的工作; 这是代码:

public static void Main()
{
    Thread.CurrentThread.Name = "Main";

    // Create a task and supply a user delegate by using a lambda expression. 
    Task taskA = new Task( () => Console.WriteLine("Hello from taskA."));
    // Start the task.
    taskA.Start();

    // Output a message from the calling thread.
    Console.WriteLine("Hello from thread '{0}'.", 
                  Thread.CurrentThread.Name);
    taskA.Wait();
}

public static void Main()
{
    Thread.CurrentThread.Name = "Main";

    // Define and run the task.
    Task taskA = Task.Run( () => Console.WriteLine("Hello from taskA."));

    // Output a …
Run Code Online (Sandbox Code Playgroud)

.net c# task-parallel-library async-await

129
推荐指数
2
解决办法
6万
查看次数

什么时候Task.Run(Action,CancellationToken)抛出TaskCanceledException?

根据文档 在任务被取消时Task.Run(Action, CancellationToken)抛出TaskCanceledException.

什么时候Task.Run(Action, CancellationToken)TaskCanceledException?目前尚不清楚抛出此异常必须满足哪些条件.

.net c# task-parallel-library

6
推荐指数
1
解决办法
3463
查看次数

为什么抛出TaskCanceledException并且不会总是进入调试器

我正在深入研究这个async-await机制并观察到了一个TaskCanceledException我无法解释的问题.

在下面的示例中(自包含)我有声明

await Task.Run(() => null);
Run Code Online (Sandbox Code Playgroud)

我知道这个声明本身是无用的,但我把问题分开了,真正的代码有逻辑,在某些情况下返回null.

为什么这会抛出TaskCanceledException?如果我返回一个任意数字(在下面的例子中为5),它就不会抛出.

此外,如果我await的方法VS的调试器中断,但如果我不这样做await,那么只有一条消息写入VS的输出窗口.

internal class Program
{
    private static void Main(string[] args)
    {
        var testAsync = new TestAsync();

        // Exception thrown but the debugger does not step in. Only a message is logged to the output window
        testAsync.TestAsyncExceptionOnlyInTheOutputWindow();

        // Exception thrown and the debugger breaks
        testAsync.TestAsyncExceptionBreaksIntoTheDebugger();

        Console.ReadKey();
    }
}

internal class TestAsync
{
    public async void TestAsyncExceptionOnlyInTheOutputWindow()
    {
         TestNullCase();
    }

    public async void TestAsyncExceptionBreaksIntoTheDebugger() …
Run Code Online (Sandbox Code Playgroud)

.net c# task-parallel-library async-await

4
推荐指数
1
解决办法
5503
查看次数

标签 统计

.net ×3

c# ×3

task-parallel-library ×3

async-await ×2