解决 当异步方法运行时,什么也没有发生

龙4ik

会员
已加入
2020年10月24日
留言内容
16
编程经验
Beginner
我在异步编程方面很糟糕,因此尝试制作一个简单的程序,这应该巩固我的知识。但是当我编译代码时,什么也没发生
这是我的代码:
C#:
static void Main(string[] args)
        {
           

            int x,y;

            x = y = 0;

            string str = "abcd";

            ASyncGet(x,y,str);
        }

static async void ASyncGet(int i1,int i2, string str)
        {
            Task t1 = Task.Run(()=>Get1(str));
            Task t2 = Task.Run(() => Get2(str));

            await Task.WhenAll(t1, t2);

         
        }

        static int Get(string str)
        {
            int i = 0;

            for (int j = 0; j < str.Length; j++)
            {
                i++;
                Console.WriteLine(str[j]);
            }

            return i;
        }

        static async Task<int> Get1(string str)
        {
            return await Task.Run(() =>Get(str));
        }

        static async Task<int> Get2(string str)
        {
            return await Task.Run(() => Get(str));
        }

我尝试调试,但过程在此行停止:
C#:
 await Task.WhenAll(t1, t2);

请,您能帮忙解释一下,我做错了吗?
附言先感谢您
 
Last edited:
Solution
You should NEVER declare a method async void unless it is an event handler. Otherwise, a method that would be declared void if synchronous should be declared async Task. If you declare your ASyncGet method that way then you can actually wait for it to complete. As it stands, you call that method 和, because it is asynchronous, it returns immediately 和 then your application quits. You need to await that task to see the results of what it does.

金西尼

C#论坛主持人
工作人员
已加入
2011年4月23日
留言内容
3,501
地点
悉尼,澳大利亚
编程经验
10+
You should NEVER declare a method async void unless it is an event handler. Otherwise, a method that would be declared void if synchronous should be declared async Task. If you declare your ASyncGet method that way then you can actually wait for it to complete. As it stands, you call that method 和, because it is asynchronous, it returns immediately 和 then your application quits. You need to await that task to see the results of what it does.
 

金西尼

C#论坛主持人
工作人员
已加入
2011年4月23日
留言内容
3,501
地点
悉尼,澳大利亚
编程经验
10+
I just tested your code 和, even as it is, it still works if you add a Console.ReadLine call at the end of the Main method. You don't get to see the console output because the application quits too quickly. With that call there the app will wait for you to close it 和 you will see the output. That's pretty much the same as any synchronous console app.
 
最佳 底部