Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RunSynchronously may not be called on task that was already started

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?

like image 686
amateur Avatar asked May 11 '12 17:05

amateur


People also ask

How do you use RunSynchronously?

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.

How do I start a new task in C#?

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();

Does Task run create new thread?

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.


2 Answers

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(); 
like image 173
Tejs Avatar answered Oct 16 '22 17:10

Tejs


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

like image 24
Peter Ritchie Avatar answered Oct 16 '22 15:10

Peter Ritchie