gpt4 book ai didi

c# - 在主线程继续任务

转载 作者:太空狗 更新时间:2023-10-29 23:09:21 24 4
gpt4 key购买 nike

我知道有一个类似的问题:ContinueWith a Task on the Main thread

但这个问题更多是针对 wpf 的,我似乎无法让它在控制台应用程序上运行。

我想在不同的线程上执行一个方法,当该方法完成后,我想继续在主线程上执行。我不想加入方法。无论如何,这就是我所拥有的:

class Program
{
static void Main(string[] args)
{
Thread.CurrentThread.Name = "MAIN";

DoWork(x =>
{
Console.Write("Method successfully executed. Executing callback method in thread:" +
"\n" + Thread.CurrentThread.Name);
});

Console.Read();
}

static void DoWork(Action<bool> onCompleteCallback)
{
Console.Write(Thread.CurrentThread.Name); // show on what thred we are executing

Task doWork = new Task(() =>
{
Console.Write(Thread.CurrentThread.Name); // show on what thred we are executing
Thread.Sleep(4000);
});

Action<Task> onComplete = (task) =>
{
onCompleteCallback(true);
};

doWork.Start();

// this line gives an error!
doWork.ContinueWith(onComplete, TaskScheduler.FromCurrentSynchronizationContext());
}
}

如何在主线程上执行 onCompleteCallback 方法?

最佳答案

but that question is more toward wpf and I cannot seeem to make it work on a console application.

您无法在控制台应用程序中执行此操作(无需大量工作)。 TPL 中内置的用于将调用编码回线程的机制都依赖于安装了 SynchronizationContext 的线程。这通常由用户界面框架安装(即:Windows 窗体中的 Application.Run,或 WPF 的启动代码等)。

在大多数情况下,它工作因为主线程有一个消息循环,框架可以将消息发布到消息循环,然后获取并运行代码。对于控制台应用程序,它只是一个“原始”线程 - 没有可以放置消息的消息循环。

当然,您可以安装自己的上下文,但这会增加很多可能没有必要的开销。


在控制台应用程序中,通常不需要“返回”到控制台线程。通常,您只需等待任务,即:

class Program
{
static void Main(string[] args)
{
Thread.CurrentThread.Name = "MAIN";

Task workTask = DoWork();

workTask.Wait(); // Just wait, and the thread will continue
// when the work is complete

Console.Write("Method successfully executed. Executing callback method in thread:" +
"\n" + Thread.CurrentThread.Name);
Console.Read();
}

static Task DoWork()
{
Console.Write(Thread.CurrentThread.Name); // show on what thred we are executing

Task doWork = new Task(() =>
{
Console.Write(Thread.CurrentThread.Name); // show on what thred we are executing
Thread.Sleep(4000);
});

doWork.Start();

return doWork;
}
}

关于c# - 在主线程继续任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12285180/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com