Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Task executed in one Thread

May I rely on the fact a Task is always executed in one thread? It can be any, but it should be the same for the whole body, as I need the thread's Culture to be set properly.

Task bind = Task.Factory.StartNew(() =>
{
    Thread.CurrentThread.CurrentCulture = culture;

    // do some asp.net binding stuff with automatic
    // date formatting

    gridView.DataSource = table;
    gridView.DataBind();
}

If I can't, is there a parameter or so to get this behaviour?

Cheers, Matthias

like image 842
Matthias Meid Avatar asked Jun 28 '11 10:06

Matthias Meid


People also ask

Can a thread have multiple tasks?

To perform multiple tasks by multiple threads, we need to use multiple run() methods. In this example; we need to extend the thread to perform multiple tasks. In this example, we use an anonymous class that extends the Thread class. In this example, we use an anonymous class that implements the Runnable interface.

How many tasks can a thread handle?

If by "in parallel" you mean "processed in parallel" and if you consider awaited Tasks, then there is no upper-bound limit on how many tasks are being awaited - but only one will actually be executed per a single CPU hardware-thread (usually 2x the CPU core count due to superscalar simultaneous multithreading, aka ...

Does Task run Use thread pool?

The main purpose of Task. Run() is to execute CPU-bound code in an asynchronous way. It does this by pulling a thread from the thread pool to run the method and returning a Task to represent the completion of the method.

Is Task same as thread in C#?

Differences Between Task And Thread Here are some differences between a task and a thread. The Thread class is used for creating and manipulating a thread in Windows. A Task represents some asynchronous operation and is part of the Task Parallel Library, a set of APIs for running tasks asynchronously and in parallel.


1 Answers

I believe the code specified for any particular task will be executed on one thread - but continuations may not be. It would be extremely hard to write valid code if tasks were thread-agile within the body of the task so I'm pretty sure you're okay.

On the other hand, your code may end up being cleaner if you use the culture explicitly wherever it's relevant. That may not be feasible depending on the ASP.NET side of things, but it's worth considering if possible.

like image 190
Jon Skeet Avatar answered Oct 23 '22 05:10

Jon Skeet