1

I am writing a program that controls some hardware via a serial port. The program will run various function based on user input. I need a way to queue these tasks and execute them synchronously on the same thread. I also need to be able to cancel them and track their status.

So I was thinking I could use tasks and chain them together using Task.ContinueWith. Will this be sufficient to force them on the same thread?

The other way I could do this is create a thread and run a continuous loop that checks a queue. The queue would hold delegates to the methods I need to run. This seems like reinventing the wheel though.

4
  • 1
    Why is it important they are on the same thread? If they are different threads but guaranteed to only run one at a time, what is the problem? – whatsisname Sep 23 '16 at 17:55
  • I can think of two possible reasons: threads have a cost, and keeping it on the same thread avoids the need to Invoke(). – Robert Harvey Sep 23 '16 at 18:14
  • @RobertHarvey: there are many good reasons, but different reasons will have different implications and limitations on what the solution is. – whatsisname Sep 23 '16 at 18:22
  • Why do you even need to use tasks? Is it not simpler to simply have a list of Action ? – Esben Skov Pedersen Sep 23 '16 at 18:40
3

You can use the Task.RunSynchronously Method.

Ordinarily, tasks are executed asynchronously on a thread pool thread and do not block the calling thread. Tasks executed by calling the RunSynchronously() method are associated with the current TaskScheduler and are run on the calling thread. If the target scheduler does not support running this task on the calling thread, the task will be scheduled for execution on the scheduler, and the calling thread will block until the task has completed execution.

.ContinueWith() runs asynchronously. Even though the next Task doesn't start until the previous Task completes, there's no guarantee that you'll be on the same thread.

You can also do this:

Task.Factory.StartNew(() => { First(); Second(); });

or this:

void MyCompositeTask()
{
  var result = First();
  Second(result);
}
Task.Factory.StartNew(() => MyCompositeTask());

both of which will stay on the same thread.

Further Reading
Continuation Task in the same thread as previous

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.