27 Ocak 2021 Çarşamba

C# Kullanıcı arayüzü (UI) donmadan async metod kullanımı

Sayfamıza bir adet buton ve bir adet label ekleyelim.

Yeni thread açmadan async şekilde fonksiyon çalıştırma yöntemi:

private async void button1_Click(object sender, EventArgs e)     
{           
        var t = Task.Factory.StartNew(async () =>
                {
                     for (int i = 0i < 1000000i++)
                     {
                        await Task.Delay(1);
                        label1.Text = i.ToString();
                     }
                },CancellationToken.None,
                TaskCreationOptions.None,
                TaskScheduler.FromCurrentSynchronizationContext());
 }

------------------------------------------------------------------------------------------------

Yeni thread açarak (eski tarz) async metod çalıştırma yöntemi:

public
Form1()
{
     InitializeComponent();
     Control.CheckForIllegalCrossThreadCalls = false;
 }

private async void button1_Click(object sender, EventArgs e)
{
            await Task.Run(() =>
            {
                for (int i = 0; i < 1000000; i++)
                {
                    label1.Text = i.ToString();
                }
            });
}

Bu yöntem daha fazla thread oluşturarak işlemciyi daha fazla yoracaktır.

Hiç yorum yok:

Yorum Gönder