I was reading about async/await recently and I would like to know how to share data between different threads which belong to different classes? Let's assume that we have the HttpContext in some web application. This context contains information about userId, sessionId and so on. Our web application gives some data which is used by some console application which executed on another computer. If errors are occurred in this console application I will write it to a log file. userId and sessionId also should written to this log file. But each thread created in this console application has its own context. So, I'm looking for a way to set userId and sessionId to thread context. I don't want to use some static classes or volatile fields. I put a simple example of my console application below.
public sealed class MainService
{
/// <summary>
/// The main method which is called.
/// </summary>
public void Execute()
{
try
{
searchService.ExecuteSearchAsync().Wait();
}
catch (Exception e)
{
// gets additional info (userId, sessionId) from the thread context
StaticLoggerClass.LogError(e);
}
}
}
public sealed class SearchService
{
private IRepository repository = new Repository();
public async Task ExecuteSearchAsync()
{
try
{
var result = await this.GetResultsAsync();
}
catch (Exception e)
{
// gets additional info (userId, sessionId) from the thread context
StaticLoggerClass.LogError(e);
}
}
private async Task<ResultModel> GetResultsAsync()
{
var result = this.repository.GetAsync();
}
}
public sealed class Repository
{
private IClient client;
public async Task<Entity> GetAsync()
{
return await client.GetResultAsync();
}
}
It is almost never necessary to have data 'set to the thread context', so put that out of your head.
It is good that you are considering thread safety - most problems come because people do not. However, in this case there is no need for 2 reasons:
from what you say, userId and sessionId do not change during the life of this example. Many requests might run at the same time, but each stack will have its own userid/sessionid
I'm betting userid/sessionid are immutable types - ie cannot be changed. This is the case if they are strings, or ints, or any value type.
So with that in mind you could do this: