2017-10-11 103 views
0

我试图使用AsyncEnumerator从https://www.nuget.org/packages/AsyncEnumerator/AsyncEnumerator不是等待任务

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

我叫async 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); 
    } 
+0

'字符串日志+ = fillData_Async(Concurrent_PhoneNoList);'我很惊讶,这甚至编译没有'await'或调用'.Result'属性。 –

+0

看来发生的情况是Form1_Load没有等待异步方法完成,然后在方法仍在运行时调用Application.Exit()。 –

+0

是的它编译,它不应该是这样吗? –

回答

0

你不等待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) 
{ 
    ... 
+0

加入.Result的作品,谢谢! –

+0

使用'AsyncMethod()。由于可能的死锁,“结果”对于“真正”异步方法是错误的方法。但它将在OP的情况下工作,只是因为他的代码显然是同步的,没有异步方法。 '等待callServiceServiceTask(item.phoneNo);'将同步执行,因为它返回已经完成的任务。 – Fabio

+0

嗨,只是为了更新,我改变了一些东西后,.Result导致死锁,Form1_Load异步方法工作 –