如何从MVC控制器操作调用异步方法?

时间:2014-11-10 19:48:41

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

我想调用异步方法,该方法在Controller中的action方法中返回一个列表。 但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;

    }

1 个答案:

答案 0 :(得分:1)

尝试

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

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