2016-04-11 42 views
1

我需要在我的C#代碼中調用SendEmail()以便我的程序不會因爲SendEmail()方法花費很多時間和/或失敗而被阻止。調用方法,以便程序不會被阻止

這裏是我的C#代碼:?(我使用.NET 4.5)

private void MyMethod() 
{ 
    DoSomething(); 
    SendEmail(); 
} 

我也能達到同樣使用下面請或有任何其他更好的辦法是使用異步/等待下一個更好的方法爲了實現這個?

public void MyMethod() 
     { 
      DoSomething(); 

      try 
      { 
       string emailBody = "TestBody"; 
       string emailSubject = "TestSubject"; 

       System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(SendEmailAlert), arrEmailInfo); 
      } 
      catch (Exception ex) 
      { 
       //Log error message 
      } 

     } 

     private void SendEmailAlert(object state) 
     { 
      string[] arrEmailnfo = state as string[]; 
      MyClassX.SendAlert(arrEmailnfo[0], arrEmailnfo[1]); 
     } 

而且萬一我需要做SendEmailAlert()方法,發射後不管,我可以用這樣的代碼這是正確? ---->

Task.Run(()=> SendEmailAlert(arrEmailInfo)); 

謝謝。

+1

查找到異步/等待 –

+0

您可以使用線程,但它可能是最好使用異步爲此/等待。 – ChrisF

回答

0

異步等待肯定可以幫助你。如果CPU限制工作異步執行,則可以使用Task.Run()。此方法可以「等待」,以便代碼在任務完成後恢復。

這是我會在你的情況做:

public async Task MyMethod() 
{ 
    DoSomething(); 

    try 
    { 
     string emailBody = "TestBody"; 
     string emailSubject = "TestSubject"; 

     await Task.Run(()=> SendEmailAlert(arrEmailInfo)); 

     //Insert code to execute when SendEmailAlert is completed. 
     //Be aware that the SynchronizationContext is not the same once you have resumed. You might not be on the main thread here 
    } 
    catch (Exception ex) 
    { 
     //Log error message 
    } 

} 

private void SendEmailAlert(string[] arrEmailInfo) 
{ 
    MyClassX.SendAlert(arrEmailnfo[0], arrEmailnfo[1]); 
} 
+0

非常感謝。並且如果我需要使SendEmailAlert()方法成爲火災並忘記,我可以刪除await關鍵字並像下面那樣使用它。這是否正確? ----> Task.Run(()=> SendEmailAlert(arrEmailInfo)); –

+0

@Vineetv是的,在這種情況下,你可以刪除await! –