Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9009001
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T02:05:10+00:00 2026-06-16T02:05:10+00:00

BEGIN EDIT The right way to do this (pre-4.5) is to use the SynchronizationContext

  • 0

BEGIN EDIT

The “right” way to do this (pre-4.5) is to use the SynchronizationContext as outlined here: http://msdn.microsoft.com/en-us/magazine/gg598924.aspx

I believe that in 4.5 SynchronizationContext is automatically handled for you with the async/await keywords, but haven’t done enough work to confirm.

In 4.0, you may want to utilize “TaskScheduler.FromCurrentSynchronizationContext” to capture the current thread’s context (in my case, this will include HttpContext, but various parts of the BCL provide similar constructs).

END EDIT

The primary question is:

Is the following a “safe” mechanism for sharing “context” with a task?

Without going into too much detail, in my use case, it’s not possible to push the context down into the action directly.

public static class ContextCaller{
    [ThreadStatic]
    public static object SharedState;

    public static Task InvokeWithContext(this Action theAction){
        //We're still running in the "outer" context, 
        //so we can collect a variable and store it in the thread-static
        //field by closing it into the task.
        var context = new object();

        var t = new Task(()=>{
            try{
                //close in the context
                SharedState = context;
                theAction();
            }
            finally{
                //teardown the shared state.
                SharedState = null;
            }
        });
        t.Start();
        return t;
    }
}

And now the client code:

//client code:
Action doWork = ()=>{
    var state = ContextCaller.SharedState;
    //do work on state, potentially throwing an exception in the process.
};

//cause the task to be invoked with some data available only on this thread.
doWork.InvokeWithContext();

Based on my understanding of the relationship between a task an a thread, the above should be safe, because:

  1. One task will run on exactly one thread (with the assumption that the action does not spawn additional tasks/threads).
  2. The ThreadStatic field is set
    before execution of “theAction()”, and “finally” guarantees this field is
    reset following the call to “theAction()”, regardless of outcome.

Aside from explicitly closing in the parameters to “theAction”, are there other, better, patterns for defining context on a Task?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-16T02:05:12+00:00Added an answer on June 16, 2026 at 2:05 am

    I don’t see any technical reason why your code shouldn’t work fine.

    But I also think doing this is a bad practice and I would use something like this only if there really isn’t any other way. And I think that adding another overload of your method that takes Action<object> (or even better, using a strongly-typed parameter) shouldn’t be a significant change.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

To begin with, I'm not even sure, if it is the right way to
EDIT: Firefox 2 windows XP Steps to reproduce problem: Firefox 2 and visit: http://resopollution.com/rentfox/html/property_setup.html
I adapted this tutorial (http://www.screaming-penguin.com/node/7749) to an Android app I've built to allow for
begin . . . # error occurs here . . . rescue => error
I'm in the middle of designing http://www.vanessacaroline.com and in need of a bit of
Hey there! I'm doing this project and right now I'm trying to: create some
I have syntax error when I use declare : delimiter $$ begin declare @StartDay
I don't know whether this question can be answered here, but I hope it
I want to avoid mouse right click on the edit boxes of my application
I have one question regarding trigger. The scenario is like this Create Procedure begin

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.