Skip to content

Update ThreadStatic example #11094

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged

Conversation

AaronRobinsonMSFT
Copy link
Member

Summary

The examples provided an initialization of ThreadStatic fields, which is a bad example for how they should be used. Removed that and made the example explicitly initialize them for each thread.

@AaronRobinsonMSFT AaronRobinsonMSFT requested a review from a team as a code owner March 14, 2025 19:11
@github-actions github-actions bot added the needs-area-label An area label is needed to ensure this gets routed to the appropriate area owners label Mar 14, 2025
@AaronRobinsonMSFT
Copy link
Member Author

/cc @gewarren @davidwrighton @jkotas

Copy link

Learn Build status updates of commit 30943f6:

✅ Validation status: passed

File Status Preview URL Details
snippets/csharp/System/ThreadStaticAttribute/Overview/threadsafe2a.cs ✅Succeeded View
snippets/fsharp/System/ThreadStaticAttribute/Overview/threadsafe2a.fs ✅Succeeded View
snippets/visualbasic/VS_Snippets_CLR_System/system.threadstaticattribute/vb/threadsafe2a.vb ✅Succeeded View

For more details, please refer to the build report.

For any questions, please:

Copy link

Learn Build status updates of commit cc9d1be:

✅ Validation status: passed

File Status Preview URL Details
snippets/csharp/System/ThreadStaticAttribute/Overview/threadsafe2a.cs ✅Succeeded View
snippets/fsharp/System/ThreadStaticAttribute/Overview/threadsafe2a.fs ✅Succeeded View
snippets/visualbasic/VS_Snippets_CLR_System/system.threadstaticattribute/vb/Program.vbproj ✅Succeeded
snippets/visualbasic/VS_Snippets_CLR_System/system.threadstaticattribute/vb/threadsafe2a.vb ✅Succeeded View

For more details, please refer to the build report.

For any questions, please:

@jkotas
Copy link
Member

jkotas commented Mar 15, 2025

I think this is a poor sample for ThreadStatics to start with. It does not demonstrate a situation where ThreadStatic must be used (local variable would work just fine - all uses are in scope of a single method) and it has a bunch of irrelevant clutter.

With help of ChatGPT, I would modify the sample to something like this:

using System;
using System.Threading;

class Program
{
    [ThreadStatic]
    private static string? _requestId;

    static void Main()
    {
        Thread thread1 = new Thread(ProcessRequest);
        Thread thread2 = new Thread(ProcessRequest);

        thread1.Start("REQ-001");
        thread2.Start("REQ-002");

        thread1.Join();
        thread2.Join();

        Console.WriteLine("Main thread execution completed.");
    }

    static void ProcessRequest(object? requestId)
    {
        // Assign the request ID to the thread-static field
        _requestId = requestId as string;

        // Simulate request processing across multiple method calls
        PerformDatabaseOperation();
        PerformLogging();
    }

    static void PerformDatabaseOperation()
    {
        Console.WriteLine($"Thread {Thread.CurrentThread.ManagedThreadId}: Processing DB operation for request {_requestId}");
    }

    static void PerformLogging()
    {
        Console.WriteLine($"Thread {Thread.CurrentThread.ManagedThreadId}: Logging request {_requestId}");
    }
}

@AaronRobinsonMSFT
Copy link
Member Author

@jkotas Thanks. Used Copilot to create F# and VB.Net versions.

Copy link

Learn Build status updates of commit 0afabb5:

✅ Validation status: passed

File Status Preview URL Details
snippets/csharp/System/ThreadStaticAttribute/Overview/Project.csproj ✅Succeeded
snippets/csharp/System/ThreadStaticAttribute/Overview/threadsafe2a.cs ✅Succeeded View
snippets/fsharp/System/ThreadStaticAttribute/Overview/threadsafe2a.fs ✅Succeeded View
snippets/visualbasic/VS_Snippets_CLR_System/system.threadstaticattribute/vb/Program.vbproj ✅Succeeded
snippets/visualbasic/VS_Snippets_CLR_System/system.threadstaticattribute/vb/threadsafe2a.vb ✅Succeeded View

For more details, please refer to the build report.

For any questions, please:

@DickBaker
Copy link
Contributor

I Like Jan Kotas' GPT code, but VS build raises two CA1840 Messages
Use 'Environment.CurrentManagedThreadId' instead of 'Thread.CurrentThread.ManagedThreadId'

so after applying the analyzer fixes and Code Cleanup, imho the C# code should become

class Program
{
    [ThreadStatic]
    static string? _requestId;

    static void Main()
    {
        var thread1 = new Thread(ProcessRequest);
        var thread2 = new Thread(ProcessRequest);

        thread1.Start("REQ-001");
        thread2.Start("REQ-002");

        thread1.Join();
        thread2.Join();

        Console.WriteLine("Main thread execution completed.");
    }

    static void ProcessRequest(object? requestId)
    {
        // Assign the request ID to the thread-static field
        _requestId = requestId as string;

        // Simulate request processing across multiple method calls
        PerformDatabaseOperation();
        PerformLogging();
    }

    static void PerformDatabaseOperation() => Console.WriteLine($"Thread {Environment.CurrentManagedThreadId}: Processing DB operation for request {_requestId}");

    static void PerformLogging() => Console.WriteLine($"Thread {Environment.CurrentManagedThreadId}: Logging request {_requestId}");
}

Copy link

Learn Build status updates of commit 431d9f6:

✅ Validation status: passed

File Status Preview URL Details
snippets/csharp/System/ThreadStaticAttribute/Overview/Project.csproj ✅Succeeded
snippets/csharp/System/ThreadStaticAttribute/Overview/threadsafe2a.cs ✅Succeeded View
snippets/fsharp/System/ThreadStaticAttribute/Overview/threadsafe2a.fs ✅Succeeded View
snippets/visualbasic/VS_Snippets_CLR_System/system.threadstaticattribute/vb/Program.vbproj ✅Succeeded
snippets/visualbasic/VS_Snippets_CLR_System/system.threadstaticattribute/vb/threadsafe2a.vb ✅Succeeded View

For more details, please refer to the build report.

For any questions, please:

@DickBaker
Copy link
Contributor

DickBaker commented Mar 15, 2025

@AaronRobinsonMSFT et al, thanks for adopting the CA1840 suggestions in all lang flavours, but I noticed you declined the "var" changes [the long-form code looked tired to me].
However I have since re-read the .editorconfig where this legacy style seems to persist in doc-land

# Types: use keywords instead of BCL types, and permit var only when the type is clear
csharp_style_var_for_built_in_types = false:suggestion
csharp_style_var_when_type_is_apparent = false:none
csharp_style_var_elsewhere = false:suggestion

so this note is to ridicule such comment since the doc-style edict is csharp_style_var_foo = false to disable var in ALL cases (i.e. I quarrel with the assertion "permit var only when the type is clear" since var seems verboten in every case). If var is so toxic, perhaps you should amend that comment to match? </rant>

Copy link

Learn Build status updates of commit 9dfbae8:

✅ Validation status: passed

File Status Preview URL Details
snippets/csharp/System/ThreadStaticAttribute/Overview/Project.csproj ✅Succeeded
snippets/csharp/System/ThreadStaticAttribute/Overview/threadsafe2a.cs ✅Succeeded View
snippets/fsharp/System/ThreadStaticAttribute/Overview/threadsafe2a.fs ✅Succeeded View
snippets/visualbasic/VS_Snippets_CLR_System/system.threadstaticattribute/vb/Program.vbproj ✅Succeeded
snippets/visualbasic/VS_Snippets_CLR_System/system.threadstaticattribute/vb/threadsafe2a.vb ✅Succeeded View

For more details, please refer to the build report.

For any questions, please:

Copy link
Member

@jkotas jkotas left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks

@AaronRobinsonMSFT AaronRobinsonMSFT merged commit 08f4dc0 into dotnet:main Mar 16, 2025
4 checks passed
@AaronRobinsonMSFT AaronRobinsonMSFT deleted the thread_static_example branch March 16, 2025 04:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
needs-area-label An area label is needed to ensure this gets routed to the appropriate area owners
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants