简体   繁体   中英

How the Visual Studio debugger infer Value inside watch window?

In the watch window for example I see:

Name : task
Value : Id = 11, Status = WaitingToRun, Method = "Void < RetreiveFromCache > b__0()"
Type : System.Threading.Tasks.Task

So the task variable is of Type Task and I want to access to the same Value the debugger prints, particularly I am interested in the Method value ( RetreiveFromCache )

However on the task variable I have only access to .Id, .Status, etc... but not .Method

Where does the Method value come from?

How can the debugger "infer" the Method value?

Yo can override the ToString() method. This is the easy way But what you are looking for are these classes:

  • DebuggerDisplayAttribute
  • DebuggerBrowsableAttribute

See https://msdn.microsoft.com/es-es/library/ms228992(v=vs.110).aspx for more information

The Action variable of the Task object is not accessible. What you can do, is create your own class that extends the functionality of Task , while exposing the Action (which holds the information about the method to run).

A quick example:

public class CustomTask : Task
{
    private Action m_action;

    public Action Action
    {
        get { return m_action; }
    }

    public CustomTask(Action action) : base(action)
    {
        m_action = action;
    }
}

Then in your code, you can use it like this:

CustomTask ct = new CustomTask(MyMethod);

Console.WriteLine("ID: {0}, Method: {1}, Status: {2}", ct.Id, ct.Action.Method, ct.Status);
//Prints: "ID: 1, Method: Void MyMethod(), Status: Created"

ct.Start();
Console.WriteLine("ID: {0}, Method: {1}, Status: {2}", ct.Id, ct.Action.Method, ct.Status);
//Prints: "ID: 1, Method: Void MyMethod(), Status: WaitingToRun"

ct.Wait();
Console.WriteLine("ID: {0}, Method: {1}, Status: {2}", ct.Id, ct.Action.Method, ct.Status);
//Prints: "ID: 1, Method: Void MyMethod(), Status: RanToCompletion"

Note that to access information about the method, you have to access ct.Action.Method .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM