본문 바로가기
개발언어/C#

[C#] Task.WhenAll() vs WhenAny()

by 창용이랑 2023. 5. 12.
728x90

- WhenAll()

  Task들이 모두 종료된 후 await 반환

 

using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace tstTst
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            label1.Text = "Before";
            label2.Text = "";

            var _ = MainAsync();

            label1.Text = "After";

        }

        public async Task<int> MainAsync()
        {
            Task task1 = Task1();
            Task task2 = Task2();

            await Task.WhenAll(task1, task2);

            label1.Text = "MainAsync";
            return 0;
        }

        public async Task<int> Task1()
        {
            await Task.Delay(1500);
            label2.Text = "Task1";
            return 1;
        }

        public async Task<int> Task2()
        {
            await Task.Delay(3000);
            label2.Text = "Task2";
            return 2;
        }
    }
}

 

- WhenAny()

Task가 하나라도 종료되면 await반환

public async Task<int> MainAsync()
{
    Task task1 = Task1();
    Task task2 = Task2();

    // await Task.WhenAll(task1, task2);
    await Task.WhenAny(task1, task2);

    label1.Text = "MainAsync";
    return 0;
}

 

- WhenAny를 이용한 Task Timeout

private void button1_Click(object sender, EventArgs e)
{
    label1.Text = "Before";
    label2.Text = "";

    // var _ = MainAsync();
    var _ = MainAsync(1.5);

    label1.Text = "After";
}

//public async Task<int> MainAsync()
public async Task<int> MainAsync(double timeout)
{
    Task task1 = Task1();
    Task task2 = Task2();

    // await Task.WhenAny(task1, task2);
    await Task.WhenAny(task2, 
        Task.Delay(TimeSpan.FromSeconds(timeout)));

    label1.Text = "TimeOut";
    return 0;
}

 

 

출처 : https://blog.naver.com/lsunday/222528851053

'개발언어 > C#' 카테고리의 다른 글

[C#] Linq 정리하기  (0) 2023.05.17
[C#] Var와 다이나믹(Dynamic)에 대해서 이해하기  (0) 2023.05.17
[C#] Task.Run() vs Task.Factory.StartNew()  (0) 2023.05.12
[C#] Task.Run()  (0) 2023.05.12
[C#] Task.Wait() vs await Task  (0) 2023.05.12