gpt4 book ai didi

c# - 具有异步顺序任务 C# 的 TaskScheduler

转载 作者:行者123 更新时间:2023-11-30 23:29:15 26 4
gpt4 key购买 nike

我正在异步执行一些 .py 脚本。一个脚本大约需要 30 秒才能执行。可能会在两三秒的时间跨度内选择两个或更多脚本。目标是有一个调度程序,它收集所有任务并一个接一个地执行它们。应包括 FIFO 功能。我尝试了以下代码只是为了尝试 queuedTaskScheduler 的功能,但即使那样也不起作用。

QueuedTaskScheduler queueScheduler;
private TaskScheduler ts_priority1;
int pos = 0;
public Form1()
{
InitializeComponent();
queueScheduler = new QueuedTaskScheduler(targetScheduler: TaskScheduler.Default, maxConcurrencyLevel: 1);
ts_priority1 = queueScheduler.ActivateNewQueue(1);
}
private void button3_Click(object sender, EventArgs e)
{
QueueValue(pos, ts_priority1);
pos++;
}

private void button4_Click(object sender, EventArgs e)
{
changeString(pos);
pos++;
}
private void changeString (int position)
{
var bea = "This is Thread " + position + " starting";
MethodInvoker Labelupdate = delegate
{
label2.Text = bea;
};
Invoke(Labelupdate);

Thread.Sleep(3000);
bea = "Thread " + position + " is ending";

MethodInvoker Labelupdate1 = delegate
{
label2.Text = bea;
};
Invoke(Labelupdate1);
Thread.Sleep(1000);
}
private void updateLabel (string Lab)
{
MethodInvoker Labelupdate = delegate
{
label2.Text = Lab;
};
Invoke(Labelupdate);
}
private Task QueueTask(Func<Task> f, TaskScheduler ts)
{
return Task.Factory.StartNew(f, CancellationToken.None, TaskCreationOptions.HideScheduler | TaskCreationOptions.DenyChildAttach, ts);
}

private Task QueueValue(int position, TaskScheduler ts)
{
return QueueTask(async () =>
{
label2.Text = "This is Thread " + position + " starting";
Thread.Sleep(3000);
label2.Text = "Thread " + position + " is ending";
Thread.Sleep(1000);
}, ts);
}

最佳答案

我解决了。只需要一个信号量。与此Thread中的方式相同这是代码:

private static SemaphoreSlim semaphore = new SemaphoreSlim(1);
private Task QueueValue(int position, TaskScheduler ts)
{
return QueueTask(async () =>
{
await semaphore.WaitAsync();
try
{
var at = "This is Thread " + position + " starting";
updateLabel(at);
await Task.Delay(3000);
at = "Thread " + position + " is ending";
updateLabel(at);
await Task.Delay(1000);
}
finally
{

semaphore.Release();
}

}, ts);
}

非常感谢!

关于c# - 具有异步顺序任务 C# 的 TaskScheduler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35580823/

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