Accessing UI controls in Task.Run with async/await on WinForms

后端 未结 6 1516
忘了有多久
忘了有多久 2020-11-29 04:57

I have the following code in a WinForms application with one button and one label:

using System;
using System.IO;
using System.Threading.Tasks;
using System.         


        
6条回答
  •  悲&欢浪女
    2020-11-29 05:31

    I am going to give you my latest answer that I have given for async understanding.

    The solution is as you know that when you are calling async method you need to run as a task.

    Here is a quick console app code that you can use for your reference, it will make it easy for you to understand the concept.

    using System;
    using System.Threading;
    using System.Threading.Tasks;
    
    public class Program
    {
        public static void Main()
        {
            Console.WriteLine("Starting Send Mail Async Task");
            Task task = new Task(SendMessage);
            task.Start();
            Console.WriteLine("Update Database");
            UpdateDatabase();
    
            while (true)
            {
                // dummy wait for background send mail.
                if (task.Status == TaskStatus.RanToCompletion)
                {
                    break;
                }
            }
    
        }
    
        public static async void SendMessage()
        {
            // Calls to TaskOfTResult_MethodAsync
            Task returnedTaskTResult = MailSenderAsync();
            bool result = await returnedTaskTResult;
    
            if (result)
            {
                UpdateDatabase();
            }
    
            Console.WriteLine("Mail Sent!");
        }
    
        private static void UpdateDatabase()
        {
            for (var i = 1; i < 1000; i++) ;
            Console.WriteLine("Database Updated!");
        }
    
        private static async Task MailSenderAsync()
        {
            Console.WriteLine("Send Mail Start.");
            for (var i = 1; i < 1000000000; i++) ;
            return true;
        }
    }
    

    Here I am trying to initiate task called send mail. Interim I want to update database, while the background is performing send mail task.

    Once the database update has happened, it is waiting for the send mail task to be completed. However, with this approach it is quite clear that I can run task at the background and still proceed with original (main) thread.

提交回复
热议问题