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?
Tasks executed by calling the RunSynchronously method are instantiated by calling a Task or Task<TResult> class constructor. The task to be run synchronously must be in the Created state. A task may be started and run only once. Any attempts to schedule a task a second time results in an exception.
To start a task in C#, follow any of the below given ways. Use a delegate to start a task. Task t = new Task(delegate { PrintMessage(); }); t. Start();
Starting a new task queues that task for execution on a threadpool thread. Threads execute in the context of the process (eg. the executable that runs your application). If this is a web application running under IIS, then that thread is created in the context of the IIS worker process.
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();
It's already started, just use myTask.Wait()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With