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();
}
}