【问题标题】:C# - How to run multi await in one method?C# - 如何以一种方法运行多等待?
【发布时间】:2014-05-05 18:20:38
【问题描述】:

我不知道如何在单个方法中运行多个等待方法。例如我的代码如下:

      public static async Task<bool> Authenticate()
    {
        bool authen = false;
        string message = String.Empty;
        try
        {
            session = await FacebookSessionClient.LoginAsync("user_about_me,read_stream");
            fbAccessToken = session.AccessToken;
            fbFacbookID = session.FacebookId;
            await saveProfile(fbFacebookID); //error here,my app is closed at here
            authen = true;

        }
        catch (InvalidOperationException e)
        {
            authen = false;
        }
        return authen;
    }

我有方法保存配置文件

  public async static void saveProfile(string fbFacbookID)
    {
        string response = string.Empty;
        if (!string.IsNullOrEmpty(fbFacbookID))
        {
            response=await StaticClass.getJsonStream(string.Format("http://graph.facebook.com/{0}", fbFacbookID));
            JObject _object = JObject.Parse(response);
            SaveValueSetting("usernameFB",(string)_object["username"]);
        }
        else
        {
            return;
        }
    }

但是我不能运行method?那么我该如何解决呢?

【问题讨论】:

  • 为什么不能运行method?有例外吗?编译器错误?请包括method1和method2的定义。
  • 把async放在public之后,在被调用的方法名后面加上()。
  • 修复示例代码。你没有调用方法。
  • @Euphoric,@Nico Schertler:我刚刚编辑,请再次查看
  • saveProfile 可能会抛出异常。您是否已单步执行代码并检查一切是否正常?

标签: c# async-await


【解决方案1】:

您可以使用下面提到的代码。

 private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        MyMethod();
        MyMethod1();

    }
    public async Task MyMethod()
    {
        Task<int> longRunningTask = LongRunningOperation();
        //indeed you can do independent to the int result work here 

        //and now we call await on the task 
        int result = await longRunningTask;
        //use the result 
        MessageBox.Show(result.ToString());
    }
    public async Task MyMethod1()
    {
        Task<int> longRunningTask = SecondMethod();
        //indeed you can do independent to the int result work here 

        //and now we call await on the task 
        int result = await longRunningTask;
        //use the result 
        MessageBox.Show(result.ToString());
    }
    public async Task<int> LongRunningOperation() // assume we return an int from this long running operation 
    {
        await Task.Delay(5000); //5 seconds delay
        return 1;
    }

    public async Task<int> SecondMethod()
    {
        await Task.Delay(2000);
        return 1;
    }

【讨论】:

  • 这根本无法回答问题。他问为什么他的代码不起作用。您没有回答这个问题,而是回答“不知道。只需使用此代码即可。它可能无法执行您想要的操作,但可以。”
猜你喜欢
  • 2022-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多