gpt4 book ai didi

c# - 顶级任务导致错误 "The current SynchronizationContext may not be used as a TaskScheduler."

转载 作者:行者123 更新时间:2023-11-30 14:11:06 27 4
gpt4 key购买 nike

<分区>

虽然我查看了 stackoverflow 和文档,但我还没有看到答案。

如果我从计时器处理程序或在另一个任务中调用创建任务的代码,则此错误将出现在下面的 ContinueWidth 上。例如,如果它被包装在另一个任务中,该任务每隔一段时间(例如每 1 秒)创建任务,如下所示。我拥有高级任务的唯一原因是每隔一段时间创建这些低级任务。

//更高层次的任务创建

...

Task task = Task.Factory.StartNew(new Action(UpdateAllDuringInterval));

...

    private void UpdateAllDuringInterval()
{
Stopwatch stopWatch = new Stopwatch();

do
{
// Start the stopwatch
stopWatch.Start();

// Create tasks
List<Task> tasks = CreateTasksAndStart();

// Wait for the tasks to complete if testing, since want to check results
if (this._testMode)
{
Task[] taskArray = tasks.ToArray();
Task.WaitAll(taskArray);
}

if (!_testMode)
{
// Get remaining time to complete interval and sleep for that time
int remainingTimeInMilliseconds = this._pollingIntervalInMilliseconds -
(int) stopWatch.Elapsed.TotalMilliseconds;
// truncating milliseconds
if (remainingTimeInMilliseconds > 0)
Thread.Sleep(remainingTimeInMilliseconds);
// will give time to CPU. Note that using Sleep used to be frowned upon but no longer due to advantages in multitasksing/CPU utilization
}
} while (!_testMode); // continue updating stocks once per interval if not testing
}

private List<Task> CreateTasksAndStart()
{
var tasks = new List<Task>();

lock (syncLock)
{
for (int i = 0; i < _stocksToUpdate.Count; i++)
{
var item = _stocksToUpdate[i];
var initialTask = Task.Factory.StartNew(() =>
{
GetUpdatedStockInformation(item);
});
var continuationTask = initialTask.ContinueWith((antecendent) =>
{
UpdateUIWithUpdatedStockInformation();
}
, CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion,
TaskScheduler.FromCurrentSynchronizationContext());

// For testing, we want to wait on the continuation task to make sure updates are done
tasks.Add(continuationTask);
}
}
return tasks;
}

如果需要更多信息,请告诉我。也请随意告诉我这段代码的其他陷阱。谢谢!

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