我正在尝试完成以下功能,
我得到一个HttpRequest
并根据请求,我将创建一个新线程,然后为该线程设置一些数据[本地和线程特定数据],然后我将旋转线程。在线程中,我必须能够在该线程结束其生命之前的任何位置使用我在创建该线程之前初始化的数据。
我尝试了这个示例,在这里,线程内的问候变量为空。关于我如何完成这个过程的任何想法。
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);
}
}
编辑 我正在尝试完成这样的事情
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<string> greeting;
static ThreadContextData()
{
greeting = new ThreadLocal<string>(() => "");
}
public void SetThreadContext(string contextValue)
{
greeting.Value = contextValue;
}
public string GetThreadContextValue()
{
return greeting.Value;
}
public void ClearThreadContextValue()
{
greeting.Value = null;
}
}