Sam
Sam

Reputation: 15770

When to use Task.Run

I want to have a background process (console application) that reads a message queue indefinitely.

Would this be the proper use of Task.Run?

do
{
    Task.Run(() =>
    {
        using (var client = new QueueMessageClient())
        {
            var result = client.GetMessages();

            // Do something with the resulting messages
            Parallel.ForEach(result.Messages, message =>
            {

            });
        }
    });
} while (true);

Upvotes: 0

Views: 101

Answers (1)

Thomas Levesque
Thomas Levesque

Reputation: 292465

Not sure what you're trying to do, but the loop should probably be inside the lambda (and inside the using block), not around it... otherwise you'll have thousands of threads reading the message queue.

Task.Run(() =>
{
    using (var client = new QueueMessageClient())
    {
        do
        {
            var result = client.GetMessages();

            // Do something with the resulting messages
            Parallel.ForEach(result.Messages, message =>
            {

            });
        } while (true);
    }
});

Upvotes: 2

Related Questions