线程是否仍在运行或者只是 LINQPad?

nin*_*der 4 c# multithreading linqpad

免责声明 1:我理解多线程的概念,但我仍然不知道正确的实现。

免责声明 2:我根本不是在批评 LINQPad,因为它太棒了。我只是想知道我是否遗漏了一些东西。

Console.WriteLine("Completed");给出下面的代码,调用时线程是否仍在运行?

我问这个问题是因为当我在 LINQPad 中运行时,我在右下角看到Press Ctrl+Shift+F5 to cancel all thread ,但是,当我通过 VS 运行与控制台应用程序相同的代码时,它似乎终止了。我完全有可能没有正确使用任务和/或没有正确终止它们。

public class TaskRunner
{
    public async void RunTasks()
    {
        CancellationTokenSource cts = new CancellationTokenSource();
        CancellationToken ct = cts.Token;

        Task loadingTask =
            new Task(() =>
                {
                    //do something that takes a while, ie. database or service call
                    for (int i = 0; i < 10; i++)
                    {
                        Thread.Sleep(100);
                        Console.WriteLine("Loading");
                    }
                });

        Task entertainmentTask =
            new Task(() =>
                {
                    //do something until told to stop to keep user entertained
                    while (true)
                    {
                        if (ct.IsCancellationRequested)
                        {
                            break;
                        }
                        Console.WriteLine("Entertainment");
                        Thread.Sleep(50);
                    }
                }, ct);

        loadingTask.Start();
        entertainmentTask.Start();

        await Task.WhenAny(loadingTask, entertainmentTask);
        cts.Cancel();

        Console.WriteLine("Completed");
    }
}
Run Code Online (Sandbox Code Playgroud)

Joe*_*ari 6

与在 Visual Studio 中构建的普通可执行文件不同,LINQPad 在主线程完成后使进程和应用程序保持活动状态,这意味着后台线程将继续运行。

此外,当您重新运行查询时,LINQPad 会回收相同的进程/AppDomain。这是一种性能优化,并且您可以使用 LINQPad 的 Util.Cache 方法在查询运行之间缓存数据。例如:

void Main()
{
   Util.Cache (TakesSomeTime).Dump();
}

int TakesSomeTime()
{
   Thread.Sleep(2000);
   return 42;
}
Run Code Online (Sandbox Code Playgroud)

该查询第一次运行时需要两秒钟。随后的执行是即时的。