Should a background worker be a Task or a Thread?

I have a background task or thread which runs an infinite loop. There's an await where it blocks waiting for some input to process.
private async Task MyBackgroundWorker(CancellationToken cancellationToken)
{
    while(!cancellationToken.IsCancellationRequested)
    {
        try
        {
            item = myBlockingCollection.Take(cancellationToken);
            await ProcessItem(item);
        }
        catch (OperationCanceledException)
        {
            return; // cancellationToken was set to Cancelled while waiting for an item.
        }
    }
}

Open in new window

My question is, should I run this as a Task or as a Thread?

Should I run it as
this.cancellationTokenSource = new CancellationTokenSource();
var token = this.cancellationTokenSource.Token;
Task myBackgroundWorker = Task.Run( await () => { MyBackgroundWorker(token); }

Open in new window

Or, I'm starting to think this really isn't a "Task", it's more of a background worker thread, that occasionally gets stopped, and restarted (recreated), and maybe using Task is the wrong approach for this. Maybe this is more properly a Thread:
myThread = new Thread(new ThreadStart(myBackgroundWorker(token));

Open in new window

Should this background worker loop be a Thread or a Task?
deleydAsked:
Who is Participating?
 
käµfm³d 👽Connect With a Mentor Commented:
Task.Run will create a new thread (or more appropriately, it will schedule work to the thread pool).

https://msdn.microsoft.com/en-us/library/hh195051(v=vs.110).aspx
1
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.