The code was blocked by a new form

JulYred 21 Reputation points
2022-07-12T06:06:13.5+00:00

I create a winform application,and try to execute a task in Main()

I found the code was blocked().

219753-%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE-2022-07-12-140352.png219781-%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE-2022-07-12-140300.png

It expect the result of {"start",“work”,"end" };

I hope someone can help me, thanks!

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,922 questions
{count} votes

Accepted answer
  1. Viorel 119.9K Reputation points
    2022-07-13T07:39:04.763+00:00

    Try adding a special line to Main:

    [STAThread]  
    static void Main( )  
    {  
        WindowsFormsSynchronizationContext.AutoInstall = false;  
      
        Form form = new Form( );  
        new TaskTest( ).OnWork( ).Wait( );  
    }  
      
      
    class TaskTest  
    {  
        public async Task OnWork( )  
        {  
            Trace.WriteLine( "start" );  
            await Task.Run( ( ) => { Trace.WriteLine( "work" ); } );  
            Trace.WriteLine( "end" );  
        }  
    }  
    

    However, it is not clear why one code works or hangs.

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Karen Payne MVP 35,551 Reputation points
    2022-07-12T18:11:30.777+00:00

    Greetings, do not use Wait()

    This does not block the UI

    using System;  
    using System.Diagnostics;  
    using System.Threading.Tasks;  
    using System.Windows.Forms;  
      
    namespace AsyncSimple  
    {  
        static class Program  
        {  
            [STAThread]  
            static async Task Main()  
            {  
                Application.SetHighDpiMode(HighDpiMode.SystemAware);  
                Application.EnableVisualStyles();  
                Application.SetCompatibleTextRenderingDefault(false);  
      
                await Operations.OnWorkAsync();  
      
                Application.Run(new Form1());  
            }  
        }  
      
        public class Operations  
        {  
            public static async Task OnWorkAsync()  
            {  
                await Task.Run(() => Debug.WriteLine($"In {nameof(OnWorkAsync)} hanging out."));  
            }  
        }  
    }  
      
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.