【问题标题】:How can I call an asyc method from MVC controller action?如何从 MVC 控制器操作中调用异步方法?
【发布时间】:2014-11-11 03:57:26
【问题描述】:

我想调用一个异步方法,它在控制器的操作方法中返回一个列表。 但是 Action 方法不是异步方法。如何修改它以便我可以在操作中调用异步方法?

public ActionResult AdvisorsMapCompleted()
    {
        List<AdvisorMapInfo> infos = await AdvisorsMapBL.getAdvisorsAsync();
        //task.Wait();


    }

public static async Task<List<AdvisorMapInfo>> getAdvisorsAsync()
    {
        var auth = new AuthenticationClient();
        //Authenticate with Salesforce
        var url = IsSandboxUser.Equals("true", StringComparison.CurrentCultureIgnoreCase)
            ? "https://test.salesforce.com/services/oauth2/token"
            : "https://login.salesforce.com/services/oauth2/token";

        await auth.UsernamePasswordAsync(ConsumerKey, ConsumerSecret, Username, Password, url);           
        var client = new ForceClient(auth.InstanceUrl, auth.AccessToken, auth.ApiVersion);
        const string qry = "SELECT Name,Primary_Contact__c,Asset_Range_Lower__c,Asset_Range_Upper__c,BillingAddress FROM Account WHERE (Account_Type__c='Advisor' or Account_Type__c='provider')";
        var accts = new List<AdvisorMapInfo>();
        var results = await client.QueryAsync<AdvisorMapInfo>(qry);
        var totalSize = results.totalSize;
        accts.AddRange(results.records);
        var nextRecordsUrl = results.nextRecordsUrl;
        if (!String.IsNullOrEmpty(nextRecordsUrl))
        {
            while (true)
            {
                var continuationResults = await    client.QueryContinuationAsync<AdvisorMapInfo>(nextRecordsUrl);
                totalSize = continuationResults.totalSize;
                accts.AddRange(continuationResults.records);
                if (string.IsNullOrEmpty(continuationResults.nextRecordsUrl)) break;
                nextRecordsUrl = continuationResults.nextRecordsUrl;
            }
        }
        return accts;

    }

【问题讨论】:

    标签: c# asp.net-mvc asynchronous salesforce async-await


    【解决方案1】:

    试试

    public async Task<ActionResult> AdvisorsMapCompleted()
        {
            List<AdvisorMapInfo> infos = await AdvisorsMapBL.getAdvisorsAsync();
            //task.Wait();
        }
    

    如果您将控制器操作方法的签名更改为上述内容,则应该可以解决问题。

    【讨论】:

      猜你喜欢
      • 2014-07-14
      • 1970-01-01
      • 2015-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多