AsyncEnumerator不等待任务

时间:2017-10-11 16:27:20

标签: c# asynchronous

我正在尝试使用https://www.nuget.org/packages/AsyncEnumerator/

中的AsyncEnumerator

所以我写的方法与他们的例子完全一样,但是,我的任务不是等待应该在哪里,只是退出程序。

我调用了异步fillData_async,里面有一个parallelloop,它运行我的长任务,应该等待。

    private void Form1_Load(object sender, EventArgs e)
    {

        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();

        ConcurrentBag<phoneData> Concurrent_PhoneNoList = new ConcurrentBag<phoneData>();

        using (SqlCommand cmd = new SqlCommand("Select * FROM numbers", conn))
        {
            conn.Open();
            SqlDataReader reader = cmd.ExecuteReader();

            while (reader.Read())
            {
                phoneData temp = new phoneData();

                int phoneno = 0;

                if (int.TryParse(reader["number"].ToString(), out phoneno) == true)
                {
                    temp.phoneID = (int.Parse(reader["id"].ToString()));
                    temp.phoneNo = phoneno;
                }

                Concurrent_PhoneNoList.Add(temp);
            }

            conn.Close();
        }

        string log += fillData_Async(Concurrent_PhoneNoList); // calls async here

        stopwatch.Stop(); // instantly continues without waiting
        TimeSpan ts = stopwatch.Elapsed;
        string.Format("{0}:{1}", Math.Floor(ts.TotalMinutes), ts.ToString("ss\\.ff"));

        log += "TotalTime: " + ts;

        Application.Exit();
    }

我的异步方法:

    private async Task<string> fillData_Async(ConcurrentBag<phoneData> phoneNolist)
    {
        string log = "Total Lines Retrieved From Database : " + phoneNolist.Count + "<br/>";

        int failures = 0;
        await phoneNolist.ParallelForEachAsync(async item =>
        {
            string returned_Data = await callWebServiceTask(item.phoneNo);

            if (returned_Data != "Failed")
            {
                item.Data = returned_Data;
            }
            else
            {
                //failedList1.Add(temp);
                failures++;
            }

        }, maxDegreeOfParalellism: 20);

        log += "Number of failures : " + failures;

        return log;
    }

    private Task<string> callWebServiceTask(int phoneNo)
    {
        string datareturned = myverylongtask(phoneNo); // public static string
        return Task.FromResult(datareturned);
    }

1 个答案:

答案 0 :(得分:1)

您不等待FillData_Async完成。将.Result添加到最后,或await

// note:  if you wait on a task like this from inside an async method,
// deadlocks might happen.
string log += fillData_Async(Concurrent_PhoneNoList).Result;

string log += await fillData_Async(Concurrent_PhoneNoList);

如果您选择await方法,则必须制作调用方法Async

// async void should *only* be used for event handlers
private async void Form1_Load(object sender, EventArgs e)
{
    ...