Does C# have a “ThreadLocal” analog (for data members) to the “ThreadStatic” attribute?

前端 未结 8 2242

I\'ve found the \"ThreadStatic\" attribute to be extremely useful recently, but makes me now want a \"ThreadLocal\" type attribute that lets me hav

8条回答
  •  一向
    一向 (楼主)
    2020-12-14 08:57

    I'm not sure how you're spawning your threads in the first place, but there are ways to give each thread its own thread-local storage, without using hackish workarounds like the code you posted in your question.

    public void SpawnSomeThreads(int threads)
    {
        for (int i = 0; i < threads; i++)
        {
            Thread t = new Thread(WorkerThread);
    
            WorkerThreadContext context = new WorkerThreadContext
            {
                // whatever data the thread needs passed into it
            };
    
            t.Start(context);
        }
    }
    
    private class WorkerThreadContext
    {
        public string Data { get; set; }
        public int OtherData { get; set; }
    }
    
    private void WorkerThread(object parameter)
    {
        WorkerThreadContext context = (WorkerThreadContext) parameter;
    
        // do work here
    }
    

    This obviously ignores waiting on the threads to finish their work, making sure accesses to any shared state is thread-safe across all the worker threads, but you get the idea.

提交回复
热议问题