Getting the Method Name from a Task in C#

Download full source code.

I sometimes have scenarios where I launch multiple tasks, each using a different method. When they complete, I want to know the returned value, and which method returned the value.

By default, the launched tasks get Ids in the form of an int. However, the method name is not easily accessible.

The Task does contain the method name, buried inside a messy string. The string is different depending on whether the method is local to where you launched the task, or if it is in another class.

In the following code, I launch three tasks, one uses a local method, and two are methods in another class.

Worker worker = new Worker();
var tasks = new Task<int>[]
{
    DoSomeLocalWork(1000),
    worker.DoSomeWork(2000),
    worker.DoSomeOtherWork(3000),
};

Here is an extension method that gets the method name for the two variations of Task.ToString() -

 1public static class TaskExtensions
 2{
 3    public static string MethodName(this Task task)
 4    {
 5        string taskName;
 6        string taskNameFull = task.ToString();
 7
 8        if(taskNameFull.Contains("<<<Main>"))
 9        {
10            int start = taskNameFull.IndexOf("__") + 2;
11            int end = taskNameFull.IndexOf("|");
12            int length = end - start;
13            taskName = taskNameFull.Substring(start, length);
14        }
15        else
16        {
17            int start = taskNameFull.IndexOf(",") +1;
18            int end = taskNameFull.IndexOf(">", start);
19            int length = end - start;
20            taskName = taskNameFull.Substring(start, length);
21            taskName = taskName.Replace("+<", ".");
22        }
23
24        return taskName;
25    }
26}

Usage of the extension method is very easy, just call task.MethodName() -

foreach (var task in tasks)
{
    try 
    {
        Console.WriteLine($"{task.MethodName()}. Id {task.Id}, result {await task}, status {task.Status}");
    }
    catch(OperationCanceledException ex)
    {
        Console.WriteLine($"{task.MethodName()}. Id {task.Id}, status {task.Status}, {ex.Message}");
    }
}

The code is not meant to be efficient, it is to demonstrate the steps needed.

Download full source code.

comments powered by Disqus

Related