如何调试 Task.Factory

本文关键字:Task Factory 调试 何调试 | 更新日期: 2023-09-27 18:31:57

如果我有一个给定的方法,例如:

protected Task CreateItemsAsync(object source)
{
    return Task.Factory.StartNew(() =>
    {
        ///////
        code
        ///////
     }
}

我在方法中有一堆代码,但我无法单步进入该方法。有没有办法在代码中逐步进行?

如何调试 Task.Factory

在控制台应用中尝试以下代码:

using System;
using System.Threading.Tasks;
namespace Demo
{
    public static class Program
    {
        [STAThread]
        private static void Main()
        {
            var task = test();
            Console.WriteLine(task.Result);
        }
        private static Task<int> test()
        {
            return Task<int>.Factory.StartNew(() =>
            {
                int x = 10;  // <-- Set a breakpoint here.
                int y = 5;
                int z = x/y;
                return z;
            });
        }
    }
}

在指示的行处设置断点,然后调试程序。

调试器将在指示的行处停止,您将能够单步执行线程中的其余行。