Reputation: 44625
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.
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.
Anyone got any ideas?
Upvotes: 41
Views: 35686
Reputation: 543
You tried to run again a Task or it is in state executed or canceled. Check a part of documentation below:
Task.RunSynchronously Method
Runs the Task synchronously on the current TaskScheduler.
InvalidOperationException The Task is not in a valid state to be started. It may have already been started, > executed, or canceled, or it may have been created in a manner that doesn't support direct scheduling.
Source: Docs .NET Task.RunSynchronously Method
Upvotes: 1
Reputation: 41246
The problem is that you started the task when you call TaskFactory.StartNew
- I mean, it's even in the name of the method that you are starting the task. StartNew
creates the task, then calls Start
on your behalf. =D
If you want, you can either Wait
on the task, like @Peter Ritchie said, or you can create the task manually like so:
var task = new Task(() => { ... });
task.RunSynchronously();
Upvotes: 49