Note that there are some explanatory texts on larger screens.

plurals
  1. POSpin new threads with custom data
    primarykey
    data
    text
    <p>I am trying to accomplish the following functionality,</p> <p>I get a <code>HttpRequest</code> and based on the request, i will create a new thread and then set some data for this thread [ local and thread specific data ] and then i will spin the thread. In the thread, i must be able to consume that data that i initialized before creating this thread anywhere before this thread ends its life.</p> <p>I tried this sample and here, the greeting variable inside the thread was null. Any idea of how do i accomplish this process.</p> <pre><code>class Program { [ThreadStatic] static string greeting = "Greetings from the current thread"; static void Main() { Console.WriteLine(greeting); // prints initial value greeting = "Goodbye from the main thread"; Thread t = new Thread(ThreadMethod); t.Start(); t.Join(); Console.WriteLine(greeting); // prints the main thread's copy Console.ReadKey(); } static void ThreadMethod() { // I am getting greeting as null inside this thread method. Console.WriteLine(greeting); // prints nothing as greeting initialized on main thread greeting = "Hello from the second thread"; // only affects the second thread's copy Console.WriteLine(greeting); } } </code></pre> <p><strong>EDIT</strong> I am trying to accomplish something like this</p> <pre><code>class ThreadTest { static void Main() { var tcp = new ThreadContextData(); Thread t = new Thread(ThreadMethod); tcp.SetThreadContext("hi.. from t1"); t.Start(); t.Join(); Thread t2 = new Thread(ThreadMethod); tcp.SetThreadContext("hello.. from t2"); t2.Start(); t2.Join(); Console.ReadKey(); } static void ThreadMethod() { Console.WriteLine(new ThreadContextData().GetThreadContextValue()); } } public class ThreadContextData { static ThreadLocal&lt;string&gt; greeting; static ThreadContextData() { greeting = new ThreadLocal&lt;string&gt;(() =&gt; ""); } public void SetThreadContext(string contextValue) { greeting.Value = contextValue; } public string GetThreadContextValue() { return greeting.Value; } public void ClearThreadContextValue() { greeting.Value = null; } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload