Data flow between Parent and child threads in Dotnetcore

317 views Asked by At

I am trying to maintain data between parent and its child threads in .NET Core web applications.

where I need to store the web application name and web request URL of the Parent thread and needs to use it when its child thread starts its execution. Even if the Parent thread completes its execution before its child thread starts its execution i need to maintain the parent data. I have tried Execution Context, Sync Local, Thread Local/static to maintain data between parent and child threads, and did not help.

  1. Can anyone suggest the way/ways to maintain data between parent and its child threads in .NET Core.
  2. In .NET Framework I found CallContext.LogicalSetData() and CallContext.LogicalGetData(), but .NET Core doesn't support Call Context.

Could anyone suggest us an Alternative approach for this in .Net Core?
System.Runtime.Remoting.Messaging ==> class CallContext

Thanks in Advance.

2

There are 2 answers

2
Ziaullah Khan On

Your question is more of an opinion/approach rather than a technical problem. Here is the best I can answer it.

Inter-Process Communication (IPC) is very tricky.

The idea is that you have a shared object that works in uni/bi-direction.

Consider producer/consumer pattern. Consider Redis cache.

Strong statement alert. Read/apply at your own risk/understanding

  1. I'd suggest moving away from threading. You should only create threads in .NET if you are writing an operating system :) In all the other cases you should use async/await.
  2. Also, try fitting in ConcurrentQueue<T> if that helps solve IPC. They all translate to message-broker pattern.
  3. TaskCompletionSource is another nice strategy to facilitate IPC.
0
Yaron Y On

Have you tried using AsyncLocal? In one of my libraries (.NET standard 2.0 which is consumed both by .NET core and .NET Framework) I use this object to do just what you need - share data within the same execution context (also across multiple threads)

In my example below (in my controller - .NET Core 3.1 template whether controller) you can see that even after response reached the client the data was still intact

private static readonly AsyncLocal<string> SharedData = new AsyncLocal<string>();

[HttpGet]
public IEnumerable<WeatherForecast> Get()
{    
    SharedData.Value = "SharedData";
    Console.WriteLine($"Shared data in main thread = {SharedData.Value}");
    // Output: 'Shared data in main thread = SharedData'
    Task.Factory.StartNew(() =>
    {
        Task.Delay(5_000).Wait();
        Console.WriteLine($"Shared data in delayed task = {SharedData.Value}");
        // Output: Shared data in delayed task = SharedData
    });    
    // Additional code...
}