【问题标题】:how to wait for await in async method to finish the all the executions?如何等待异步方法中的等待完成所有执行?
【发布时间】:2016-11-03 08:06:16
【问题描述】:

对于以下代码,我调用了该异步 void 方法。

  public  void LoadSystemDetails(int clientId)
    {
        DataSystem.Name = "Salesforce System";
        DataSystem.Description = "";
        GetAllFields(clientId);
    }

下面的代码是GetAllFields方法

 public async void GetAllFields(int clientId)
    {
        this.DataSystem.SystemTables = new List<DataSystemTable>();


        using (var forceClient = await ConnectToSalesforceByOAuth(clientId))
        {
              var SalesForceTable = new DataSystemTable
            {
                TableName = "Contact"
            };
            DataSystem.SystemTables.Add(SalesForceTable);

            var contact = forceClient.DescribeAsync<SalesforceObject>("Contact");
            var tableFields = new List<DataSystemField>();

            foreach (var con in contact.Result.Fields)
            {
                tableFields.Add(new DataSystemField
                {

                    ColumnName = con.Name,

                });
            }

            SalesForceTable.EissSyncSystemFields = tableFields;
      } 

我打电话给callbackScript,如下所示。

  callbackScript.AppendLine(string.Format("var destinationSystem ={0};", JsonConvert.SerializeObject(this.DestinationSystem, Formatting.Indented)));

这里DestinationSystem 正在调用LoadSystemDetails。赞DestinationSystem.LoadSystemDetails(clientId)

using (var forceClient = await ConnectToSalesforceByOAuth(clientId)) 行在callbackScript 执行时执行。所以SystemTables 没有任何价值。但它有NameDescription

所以在这里我需要等待LoadSystemDetails 完成GetAllFields

我是怎么做到的。请帮帮我。 谢谢。

【问题讨论】:

    标签: c# async-await


    【解决方案1】:

    如果需要LoadSystemDetails等待GetAllFields,这里有2个问题:

    • 您正在从同步上下文调用异步方法
    • GetAllFields 是 async void,意思是一劳永逸。您将永远无法等待它完成。

    解决方案: 首先,如果您需要等待结果或结束,切勿使用async void。请改用async Task
    其次,要么将LoadSystemDetails也转换为异步方法,然后等待GetAllFields(应该返回Task),或者使用GetAllFields(clientId).Wait()

    查看这篇文章以了解有关 async/await 的更多信息:https://msdn.microsoft.com/en-us/magazine/jj991977.aspx

    【讨论】:

      【解决方案2】:

      正如@netchkin 所说:永远不要使用async void。使用async Task。您不必自己返回Task,您仍然可以使用return;

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-02-22
        • 2013-08-19
        • 1970-01-01
        • 2013-02-15
        • 2020-10-04
        • 2018-07-17
        • 2017-11-28
        • 2011-10-04
        相关资源
        最近更新 更多