Issue regarding asynchronous Programming with Asyn

2019-03-06 17:22发布

This question already has an answer here:

i was learning how to use Async and Await c#. so i got a link http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx#BKMK_WhatHappensUnderstandinganAsyncMethod

from here i try to run the code from VS2012 IDE but getting error. this function is raising error.

private void button1_Click(object sender, EventArgs e)
        {
            int contentLength = await AccessTheWebAsync();

            label1.Text= String.Format("\r\nLength of the downloaded string: {0}.\r\n", contentLength);
        }

this line giving error await AccessTheWebAsync(); The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'

what i am doing the wrong. please guide me how to run the code. thanks

2条回答
ゆ 、 Hurt°
2楼-- · 2019-03-06 17:45

You need to put async in your method, I modified your code since the Click event signature does not return int, and your method AccessTheWebAsync does, so I moved it to another method async that returns int, anyway I async and await are kind of syntactic sugar and is recommended that you take a look at what really happens to your code when you use these keywords, take a look here: http://www.codeproject.com/Articles/535635/Async-Await-and-the-Generated-StateMachine

private async void button1_Click(object sender, EventArgs e)
        {
            await ClickAsync();
        }

        private async Task<int> AccessTheWebAsync()
        {

            return await Task.Run(() =>
                {
                    Task.Delay(10000);  //Some heavy work here
                    return 3; //replace with real result
                });

        }

        public async Task ClickAsync()
        {
            int contentLength = await AccessTheWebAsync();

            label1.Text = String.Format("\r\nLength of the downloaded string: {0}.\r\n", contentLength);
        }
    }
查看更多
Ridiculous、
3楼-- · 2019-03-06 18:03

It very clearly states that you have to decorate your method with async. Like so:

// note the 'async'!
private async void button1_Click(object sender, EventArgs e)

Have a look here: async (C# Reference).

By using the async modifier, you specify that a method, lambda expression, or anonymous method is asynchronous. If you use this modifier on a method or expression, it's referred to as an async method.

查看更多
登录 后发表回答