【问题标题】:Error with Async/Await Method [closed]异步/等待方法错误[关闭]
【发布时间】:2014-09-01 14:20:38
【问题描述】:

我在尝试一些 async 方法时收到以下错误。我正在关注这个例子:Microsoft Async Example

'await' 运算符只能在异步方法中使用

'await' 的方法是 IS async,我认为它与 Microsoft 示例几乎相同。

我在这里做错了什么?

按钮点击

private void btn_Async_Click(object sender, EventArgs e)
    {
        GeneralFeatures gf = new GeneralFeatures();
        Task<long> getLongRunningData = gf._Async();

        long answer = await getLongRunningData ;
    }

异步方法

class GeneralFeatures
{
public async Task<long> _Async()
    {
        /////  LONG RUNNING TASK  /////////
        int count = 0;
        int j = 1101000;
        long a = 2;
        while (count < j)
        {
            long b = 2;
            int prime = 1;// to check if found a prime
            while (b * b <= a)
            {
                if (a % b == 0)
                {
                    prime = 0;
                    break;
                }
                b++;
            }
            if (prime > 0)
                count++;
            a++;
        }
        /////  LONG RUNNING TASK  /////////

        return a;
    }
}

【问题讨论】:

  • private void btn_Async_Click 告诉我你在哪里将它定义为async

标签: c# asynchronous


【解决方案1】:

如果方法签名没有async,则不能有await

private void btn_Async_Click(object sender, EventArgs e) 中没有 async

应该是:private async void btn_Async_Click(object sender, EventArgs e) 试试看,或者从那个调用一个异步方法。

【讨论】:

  • 确实如此。这与链接页面上的示例相匹配,该示例将private async void startButton_Click(object sender, RoutedEventArgs e) 作为第一个方法签名。
  • @Chris 不用看,明显不见了:)
  • 这并不是为了证明您的答案是正确的,而是作为 OP 的一个亮点,即他的代码与他认为他正在复制的代码不同的地方。正如您所说,您的答案非常满意,无需外部参考。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-11
  • 1970-01-01
相关资源
最近更新 更多