开发者

.NET Task executed in one Thread

开发者 https://www.devze.com 2023-03-16 08:08 出处:网络
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.

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 开发者_StackOverflow中文版or so to get this behaviour?

Cheers, Matthias


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.


Yes, the task body is executing in one thread except the case when you starting subtasks or explicitly creating other threads (Thread, ThreadPool, etc.).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号