0

对于我的应用程序,我调用网络服务来获取客户数据。我遇到的问题是,当我进行此特定调用时,它会获取异步等待调用并在未完成调用然后存储结果的情况下循环返回。

private void DatabaseTest()
{
    cNum = Convert.ToString(db.selectCustomerNumber());
    callC = "SELECT * FROM dashboardCustomer WHERE period = 'C' AND customerNumber = " + cNum;
    callB = "SELECT * FROM dashboardCustomer WHERE period = 'B' AND customerNumber = " + cNum;
    callF = "SELECT * FROM dashboardCustomer WHERE period = 'F' AND customerNumber = " + cNum;
    if (db.selectDashboard(callC).Count == 0)
    {
        GetDataSummary(passC);
    }
    if (db.selectDashboard(callB).Count == 0)
    {
        GetDataSummary(passB);
    }
    if (db.selectDashboard(callF).Count == 0)
    {
        GetDataSummary(passF);
    }
}

    private async void GetDataSummary(string r)
    {

        long customerNum = db.selectCustomerNumber();
        pin = db.selectPinByCustomerNumber(customerNum);

        string cType = r;
        try
        {
            Windows.Security.Credentials.PasswordVault vault = new Windows.Security.Credentials.PasswordVault();
            IReadOnlyList<PasswordCredential> userCredential = vault.FindAllByResource(pin);

            userCredential[0].RetrievePassword();

            try
            {
                getCustomerBillSummaryResponse billSum = await
                    UBPclient.getCustomerBillSummaryAsync(userCredential[0].UserName, userCredential[0].Password, customerNum, cType);

                invoiceSummaryBean[] summaryList = billSum.@return;

                rh.DashboardHandler(summaryList, customerNum);


            }
            catch
            {

            }
        }
        catch
        {

        }

    }

它运行到以下部分

getCustomerBillSummaryResponse billSum = await
                    UBPclient.getCustomerBillSummaryAsync(userCredential[0].UserName, userCredential[0].Password, customerNum, cType);

然后循环回到 try 并再次运行,直到它运行了 3 次。

如何让它返回每次调用的数据并将其存储在我的数据库中?

此外,我已经在 SoapUI 中测试了 Web 服务,并且调用正在返回结果,所以问题不在于 Web 服务。

4

2 回答 2

2

你需要这样做:

private async Task GetDataSummary(string r)

您需要返回Task而不是void因为您的调用者需要等待。当您返回void时,调用者必须将方法视为“即发即弃”。当您返回Task时,调用者可以创建必要的代码来await完成异步方法。

并且不要忘记在调用时添加 await 关键字:await GetDataSummaryAsync(...);

于 2013-07-16T14:51:35.100 回答
1

你应该避免async void。更改GetDataSummary为返回Task,然后awaitDatabaseTest

private async Task DatabaseTestAsync()
{
    ...
    if (db.selectDashboard(callC).Count == 0)
    {
        await GetDataSummaryAsync(passC);
    }
    if (db.selectDashboard(callB).Count == 0)
    {
        await GetDataSummaryAsync(passB);
    }
    if (db.selectDashboard(callF).Count == 0)
    {
        await GetDataSummaryAsync(passF);
    }
}

private async Task GetDataSummaryAsync(string r)
于 2013-07-16T14:53:26.440 回答