开发者

Ambient data flow from thread to any children threads

I'm trying to enhance our server platform with the ability to track some kind of an ambient context that we define. Every context has at least an ID that may or may not be used by various parts of our platform as functional flow progresses. Within a context, threads may be created (or async invokes, or things like WF which executes on other threads). I'd like for those children threads to be able to participate in the context of the parent at least to get the ContextID.

I imagine something like the following:

using (Context ctx = Context.Create()) {
    Log.Print(Context.Current.ID);
    Task task = Task.Factory.StartNew( () => {
        Log.Print(Context.Current.ID);
        using (Context ctx2 = Context.Current.CreateC开发者_Go百科hild()) {
            Log.Print(Context.Current.ID);
        }
        ...
    }
    ...
    task.Wait();
}

So what should be printing is something like:

"ContextID1"

"ContextID1"

"ContextID1:ContextID2"

The primary purpose to help track log messages across many servers much easier than what we have now. Program and data flows between many (hundreds of) machines and it's too tedious to track from one to another. Using an ambient correlater will help immensely, the only problem I have right now is I don't know how child threads can automatically figure out what the context of the parent thread was, let alone access it's TLS. If I could get just the ManagedThreadID of the parent thead, I can make this whole thing work the way I want.

I realize I can pass the Context in as a start parameter when creating the thread/task, but there's millions of lines of code in our platform and I cannot just make changes. So to bake it into the core framework and make it perfectly ambient will solve the problem, I do have control over that.


I had been designing such a system once and I had to replace all thread-start-related code with custom wrappers that generalized and abstracted out such a context chaining as you want. Unfortunately I'm not aware of a good transparent mechanism that would solve it.

One of the problems you'll most likely face is executing code on the thread pool and requiring it to inherit the parent context. Here you need to take the fact of reusing thread pool threads into account. Every work executed on a thread pool thread will have to handle context inheritance gracefully, without influencing any unrelated piece of code that will execute on the same thread in the future.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜