Home > Back-end >  Add non-task element into existing Task<List<T>> to return from method
Add non-task element into existing Task<List<T>> to return from method

Time:01-17

What is the best way to add non-Task element to existing Task<List<MyClass>>?

I have to add MyClass element nonTaskClass into result x that is Task List. The thing is that it is not in any way async. It is just some pure conditional logic that results into object. Something like this:

public Task<List<MyClass>> CheckAsync(Input input) {
    // Get some class based on sync logic/conditional logic
    var nonTaskClass = new MyClass();
    if (input.Form == 1 || input.Country = "Lithuania") {
        nonTaskClass.Message = "Some message goes here";
    } else {
        nonTaskClass.Message = "Another message";
    }
     
    // Create tasks (calls different methods/services and get data)
    // Task list actually is based on "nonTaskClass"

    // Get data from tasks and return
    var x = Task.WhenAll(tasks).ContinueWith(t =>
    {
        return t.Result.Select(o => new MyClass
        {
            Message = o.Message
        }).ToList();
    });
    // Need to add nonTaskClass into x, how?!!!!!

    return x;
}

CodePudding user response:

If it wasn't feasible to refactor the method - including making it async - I would add Task.FromResult(nonTaskClass) to the list of tasks:

tasks.Add(Task.FromResult(nonTaskClass));

// Get data from tasks and return
var x = Task.WhenAll(tasks)...

CodePudding user response:

I would make it async and change it to:

public async Task<List<MyClass>> CheckAsync(Input input)
{
        var nonTaskClass = new MyClass();
        if (input.Form == 1 || input.Country = "Lithuania")
        {
            nonTaskClass.Message = "Some message goes here";
        }
        else
        {
            nonTaskClass.Message = "Another message";
        }

        var tasks = GetSomeTasks();

        return (await Task.WhenAll(tasks))
                .Select(x => new MyClass { Message = x.Message })
                .Append(nonTaskClass)
                .ToList();
}
  • Related