C#-如何为调用方创建堆栈ID?

时间:2018-08-26 06:42:53

标签: c# task callstack

我想为方法调用创建调用者ID,那是什么? CallerID是调用诸如Task.CurrentId之类的方法的标识,但是在这种情况下,我不想创建新线程来访问ThreadId, 例如:

    public class OperationMethodContext
{
    public static OperationMethodContext Current { get; set; }

    public int Id { get; set; }
    public string MethodName { get; set; }
    public Guid Guid { get; set; }
}

internal class Program
{
    private static void Main(string[] args)
    {
        OperationMethodContext.Current = new OperationMethodContext() {  Guid = Guid.NewGuid(), MethodName="call 1", Id = 1};
        MethodRun();
        OperationMethodContext.Current = new OperationMethodContext() {  Guid = Guid.NewGuid(), MethodName="call 2", Id = 2};
        MethodRun();
        OperationMethodContext.Current = new OperationMethodContext() {  Guid = Guid.NewGuid(), MethodName="call 3", Id = 3};
        MethodRun();
        OperationMethodContext.Current = new OperationMethodContext() {  Guid = Guid.NewGuid(), MethodName="call 4", Id = 4};
        MethodRun();
        Console.ReadKey();
    }

    private static async void MethodRun()
    {
        Console.WriteLine("call started: " + OperationMethodContext.Current.MethodName);
        await Task.Delay(2000);
        Console.WriteLine("call finished: " + OperationMethodContext.Current.MethodName);
    }
}

如果要更多调用堆栈,我想获取每个方法调用的OperationMethodContext.Current,而无需将OperationMethodContext作为参数或属性发送。

0 个答案:

没有答案