在一种方法中从多个任务返回消息

时间:2018-01-22 06:06:56

标签: c# multithreading async-await task c#-6.0

请考虑此准则:

private async Task<string> DoSomeWorkAsync()
{
    var Task1 = await Task.Run(() => 
                {
                    Thread.Sleep(3000);
                    return "Message From Task 1";
                });

    var Task2 = await Task.Run(() => 
                {
                    Thread.Sleep(1000);
                    return "Message From Task 2";
                });

    var Task3 = await Task.Run(() => 
                {
                    Thread.Sleep(3000);
                    return "Message From Task 3";
                });

    return ?????;
}

如何完成任务1的消息等等?

编辑1)

我希望表单在任务运行时响应。

2 个答案:

答案 0 :(得分:1)

试试这个。
可能它不是解决这个问题最优雅的方式,但也许它很有用。

这个在7秒后返回所有任务。

private async sometype SomeMethodAsync()
{
    List<string> _ListOfMessages = new List<string>();

    _ListOfMessages = await DoSomeWorkAsync1();
    foreach (string _message in _ListOfMessages)
        Console.WriteLine("Message: {0}", _message);
}

private async Task<List<string>> DoSomeWorkAsync1()
{
    List<string> _StringsToReturn = new List<string>();

    _StringsToReturn.Add(await Task.Run(() =>
    {
        Thread.Sleep(3000);
        return "Message From Task 1";
    }));

    _StringsToReturn.Add(await Task.Run(() =>
    {
        Thread.Sleep(1000);
        return "Message From Task 2";
    }));

    _StringsToReturn.Add(await Task.Run(() =>
    {
        Thread.Sleep(3000);
        return "Message From Task 3";
    }));

    return _StringsToReturn;
}

此时返回一个任务(在指定的延迟之后):
(编辑:忘记粘贴return _StringToReturn;

private async sometype SomeMethodAsync()
{
    for (int _Job = 1; _Job <= 3; _Job++)
    {
        string _Message = await DoSomeWorkAsync2(_Job);
        Console.WriteLine("Message: {0}", _Message);
    }
}

private async Task<string> DoSomeWorkAsync2(int _job)
{
    string _StringToReturn = string.Empty;

    switch (_job)
    {
        case 1:
        _StringToReturn = await Task.Run(() =>
        {
            Thread.Sleep(3000);
            return "Message From Task 1";
        });
        break;

        case 2:
        _StringToReturn = await Task.Run(() =>
        {
            Thread.Sleep(1000);
            return "Message From Task 2";
        });
        break;

        case 3:
        _StringToReturn = await Task.Run(() =>
        {
            Thread.Sleep(3000);
            return "Message From Task 3";
        });
        break;
    }
    return _StringToReturn;
}

如果这些任务需要级联他们的结果:
(与DoSomeWorkAsync1()相同)

private async Task<List<string>> DoSomeWorkAsync4()
{
    List<string> _StringsToReturn = new List<string>();

    _StringsToReturn.Add(await Task.Run(() =>
    {
        Thread.Sleep(3000);
        return "Task 1 completed";
    }).ContinueWith<string>(t => {

        Thread.Sleep(1000);
        return t.Result + " Task 2 completed";

    }).ContinueWith<string>(t =>{
        Thread.Sleep(3000);
        return t.Result + " Task 3 completed" + 
                            Environment.NewLine + "All tasks completed";
    }));

    return _StringsToReturn;
}

列表(类) - 启用属性值(TaskID)

public class MyTask
{
    public int TaskID { get; set; }
    public string ReturnMessage { get; set; }
}

private async sometype SomeMethodAsync()
{
    List<MyTask> _ListOfTasks = new List<MyTask>();
    _ListOfTasks.Add(new MyTask { TaskID = 1, ReturnMessage = string.Empty });
    _ListOfTasks.Add(new MyTask { TaskID = 2, ReturnMessage = string.Empty });
    _ListOfTasks.Add(new MyTask { TaskID = 3, ReturnMessage = string.Empty });

    foreach (MyTask _task in _ListOfTasks)
    {
        _task.ReturnMessage = await DoSomeWorkAsync3(_task.TaskID);
        Console.WriteLine("Message: {0}", _task.ReturnMessage);
    }


private async Task<string> DoSomeWorkAsync3(int TaskID)
{
    string _StringToReturn = string.Empty;

    _StringToReturn = await Task.Run(() =>
    {
        switch (TaskID)
        {
            case 1:
                Thread.Sleep(3000);
                return "Message From Task 1";
            case 2:
                Thread.Sleep(1000);
                return "Message From Task 2";
            case 3:
                Thread.Sleep(3000);
                return "Message From Task 3";
            default:
                return string.Empty;
        }
    });

   return _StringToReturn;
}

答案 1 :(得分:-1)

private List<Task<string>> GetSomeWork()
{
    var tasks = new List<Task<string>>();

    tasks.Add(await Task.Run(() => 
                {
                    Thread.Sleep(3000);
                    return "Message From Task 1";
                }));

    tasks.Add(await Task.Run(() => 
                {
                    Thread.Sleep(1000);
                    return "Message From Task 2";
                }));

    tasks.Add(await Task.Run(() => 
                {
                    Thread.Sleep(3000);
                    return "Message From Task 3";
                }));

    return tasks;
}


var tasks = GetSomeWork();

while (tasks.Count > 0)
{
    var task = await Task.WhenAny(tasks);
    var message = task.Result;
    tasks.Remove(task);
}