C# 不能在已经启动的任务上调用 RunSynchronously

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10555623/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 14:18:06  来源:igfitidea点击:

RunSynchronously may not be called on task that was already started

c#async-awaittask-parallel-library

提问by amateur

I am having an issue with a c# class I created for unit testing my application, in particular the issue is around a System.Threading.Tasks.Task object.

我在创建用于对我的应用程序进行单元测试的 ac# 类时遇到问题,特别是该问题与 System.Threading.Tasks.Task 对象有关。

I have a list of such objects and on them I want to execute each synchronously.

我有一个此类对象的列表,我想在它们上同步执行每个对象。

I call the following:

我称之为:

myTask.RunSynchronously();

When I do such, I am always getting the following error and I dont know why are how I can fix it.

当我这样做时,我总是收到以下错误,我不知道为什么我可以解决它。

System.InvalidOperationException: RunSynchronously may not be called on task that was already started.

System.InvalidOperationException:不能对已启动的任务调用 RunSynchronously。

Anyone got any ideas?

有人有任何想法吗?

采纳答案by Tejs

The problem is that you startedthe task when you call TaskFactory.StartNew- I mean, it's even in the name of the method that you are starting the task. StartNewcreates the task, then calls Starton your behalf. =D

问题是您在调用时启动了任务TaskFactory.StartNew- 我的意思是,它甚至在您启动任务的方法的名称中。StartNew创建任务,然后Start代表您调用。=D

If you want, you can either Waiton the task, like @Peter Ritchie said, or you can create the task manually like so:

如果你愿意,你可以Wait像@Peter Ritchie 所说的那样在任务上,或者你可以像这样手动创建任务:

var task = new Task(() => { ... });
task.RunSynchronously();

回答by Peter Ritchie

It's already started, just use myTask.Wait()

已经开始使用了 myTask.Wait()