Web API. Install each thread with the id HttpRequestMessage?

I have a web api coded in C #.

The web api uses functions that are shared by other internals. it depends on single threaded threads and uses local thread storage to store objects and session information. Please do not say whether it is good or bad that I have to deal.

In web api I have implemented a custom message handler (DelagatingHandler) using SendAsync

protected async override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)

      

which is TPL based and sometimes switches threads, and when that happens, my threading functions get confused as I lose the thread context and all data assigned to it.

My idea is to uniquely identify the HttpRequestMessage.I think using the correlation id should be sufficient for it

var requestId = request.GetCorrelationId();

      

But I want to store the HttpRequestMessage correlation ID for each thread allocated in the Task.

So my question is basically if I can define a thread that is allocated within a particular task and allocate an ID to it?

+3


source to share


1 answer


For context-related problems, you can use CallContext.LogicalSetData

and CallContext.LogicalGetData

, which is simply IDictionary<string, object>

that flows between contexts and has copy-on-write semantics.

Since your data is immutable (according to the docs ), you can map your correlation ID to your streaming thread ID:

protected async override Task<HttpResponseMessage> SendAsync(
                         HttpRequestMessage request, 
                         CancellationToken cancellationToken)
{
    var correlationId = request.GetCorrelationId();
    var threadId = Thread.CurrentThread.ManagedThreadId;

    CallContext.LogicalSetData(correlationId.ToString(), threadId);
}

      



And return later if you make sure you are in the "correct flow".

A well-read call context with async-await

can be found here .

+4


source







All Articles