gpt4 book ai didi

c# - 如何获取可等待任务的句柄?

转载 作者:太空宇宙 更新时间:2023-11-03 15:22:17 25 4
gpt4 key购买 nike

我是 Tasks 的新手,仍在学习这个主题,所以请对我温和一点(我认为我的以下代码存在一些基本问题......)

请看下面的练习,这将帮助我描述我的问题:我有一个简单的“MyService”类,它有一个由“Run”方法调用的“Do_CPU_Intensive_Job”方法。我的目的是能够运行“Do_CPU_Intensive_Job”方法的多个实例(它本身运行在与 UI 不同的线程上,因为它受 CPU 限制),有时是同步的,有时是异步的。

换句话说,假设我有 2 个 MyService 实例,有时我希望这 2 个方法同时运行,有时则不需要。

class MyService
{
private bool async;
private string name;
private CancellationTokenSource tokenSource;
private CancellationToken token;
private bool isRunning = false;
private Task myTask = null;

public MyService(string name, bool async)
{
this.name = name;
this.async = async;
}

public string Name { get { return name; } }
public bool IsRunning { get { return isRunning; } }

public async Task Run ()
{
isRunning = true;
tokenSource = new CancellationTokenSource();
token = tokenSource.Token;

if (async)
myTask = Do_CPU_Intensive_Job();
else
await Do_CPU_Intensive_Job(); // I cannot do myTask = await Do_CPU_Intensive_Job(); so how can the "Stop" method wait for it??
}

public async Task Stop ()
{
tokenSource.Cancel();

if (myTask != null)
await myTask;

isRunning = false;
}

private async Task Do_CPU_Intensive_Job ()
{
Console.WriteLine("doing some heavy job for Task " + name);
int i = 0;
while (!token.IsCancellationRequested)
{
Console.WriteLine("Task: " + name + " - " + i);
await Task.Delay(1000);
i++;
}

Console.WriteLine("Task " + name + " not yet completed! I need to do some cleanups");

await Task.Delay(2000); //simulating cleanups
Console.WriteLine("Task " + name + " - CPU intensive and cleanups done!");
}
}

所以,我有下面的 GUI,它运行良好,但前提是 2 个实例异步运行。 “运作良好”意味着当停止任务时,它通过运行整个“Do_CPU_Intensive_Job”方法很好地停止。因此,最后一条消息将来自 GUI(“两个任务都已完成......现在正在做一些其他事情”)。到目前为止一切顺利。

public partial class Form1 : Form
{
List<MyService> list = null;
MyService ms1 = null;
MyService ms2 = null;

public Form1()
{
InitializeComponent();
list = new List<MyService>();
ms1 = new MyService("task 1", true);
ms2 = new MyService("task 2", true);
list.Add(ms1);
list.Add(ms2);
}

private async void button1_Click(object sender, EventArgs e)
{
foreach (MyService item in list)
await item.Run();
}

private async void button2_Click(object sender, EventArgs e)
{
foreach (MyService item in list)
{
if (item.IsRunning)
{
await item.Stop();
Console.WriteLine("Done stopping Task: " + item.Name);
}
}

//now ready to do some other stuff
Console.WriteLine("Both tasks are completed...now doing some other stuff");
}
}

当 2 个实例未同时运行时,问题就开始了。在那种情况下,我从 GUI “Do_CPU_Intensive_Job”真正完成之前得到“两个任务都已完成...现在正在做其他事情”...

        ms1 = new MyService("task 1", false);
ms2 = new MyService("task 2", false);

当两个任务一起运行时,这不会发生,因为我在异步运行时有句柄 (myTask),而在同步运行时我没有。

await Do_CPU_Intensive_Job(); // I cannot do myTask = await Do_CPU_Intensive_Job(); so how can the "Stop" method wait for it??

谢谢大家

最佳答案

我花了一些时间敲定代码,使我认为它正在做预期的事情。

我发现的第一个问题是您不能只将取消标记传递到您的方法中,您需要将它与要取消的任务相关联。不幸的是,我找不到直接在 async 方法上执行此操作的方法,但请查看此处的 MyService 类,了解我是如何执行此操作的。

class MyService
{
private bool async;
private string name;
private CancellationTokenSource tokenSource;
private bool isRunning = false;
private Task myTask = null;

public MyService(string name, bool async)
{
this.name = name;
this.async = async;
}

public string Name { get { return name; } }
public bool IsRunning { get { return isRunning; } }

public async Task Run()
{
isRunning = true;
tokenSource = new CancellationTokenSource();

myTask = Task.Run(() => Do_CPU_Intensive_Job(tokenSource.Token), tokenSource.Token);
if (!async)
await myTask;
}

public async Task Stop()
{
tokenSource.Cancel();

if (myTask != null)
await myTask;

isRunning = false;
}

private void Do_CPU_Intensive_Job(CancellationToken token)
{
Console.WriteLine("doing some heavy job for Task " + name);
int i = 0;
while (!token.IsCancellationRequested)
{
Console.WriteLine("Task: " + name + " - " + i);
Thread.Sleep(1000);
i++;
}

Console.WriteLine("Task " + name + " not yet completed! I need to do some cleanups");

Thread.Sleep(1000);
Console.WriteLine("Task " + name + " - CPU intensive and cleanups done!");
}
}

Run 方法现在使用 Task.Run 调用 Do_CPU_Intensive_Job 如果您注意到我将 token 传递给工作方法和 Task .Run 调用。后者将 token 链接到该任务/线程,前者允许我们监视取消请求。

最后一部分是我们如何在服务实例上调用 Run,通过在 Task 或异步方法上调用 await 线程正在被释放,但方法中的其余代码被提取并将在等待的任务完成之前不会运行。

我只是使用单元测试来处理代码而不是按钮,但前提应该是相同的,但这里是我如何能够以同步模式运行任务并且仍然能够调用停止在他们身上。

var service1 = new MyService("task 1", false);
var service2 = new MyService("task 2", false);

service1.Run(); //Execution immediately moves to next line
service2.Run(); // Same here

await service1.Stop(); //Execution will halt here until task one has fully stopped so task 2 actually continues running
await service2.Stop();

关于c# - 如何获取可等待任务的句柄?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36754085/

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