调用方法,这样程序就不会被阻塞
Calling Method so that program doesn't get blocked
我需要在下面的 C# 代码中调用 SendEmail(),这样我的程序就不会因为 SendEmail() 方法花费大量时间或失败而被阻止。
这是我的 C# 代码:(我使用的是 .Net 4.5)
private void MyMethod()
{
DoSomething();
SendEmail();
}
我可以使用以下方法实现相同的效果吗?或者还有其他更好的方法吗?使用 async/await 是实现此目标的更好方法吗?
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));
谢谢。
Async await 绝对可以帮到你。当您有 CPU 绑定工作要异步执行时,您可以使用 Task.Run()
。这个方法可以"awaited"这样代码会在任务完成后继续。
对于你的情况,我会这样做:
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]);
}
我需要在下面的 C# 代码中调用 SendEmail(),这样我的程序就不会因为 SendEmail() 方法花费大量时间或失败而被阻止。
这是我的 C# 代码:(我使用的是 .Net 4.5)
private void MyMethod()
{
DoSomething();
SendEmail();
}
我可以使用以下方法实现相同的效果吗?或者还有其他更好的方法吗?使用 async/await 是实现此目标的更好方法吗?
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));
谢谢。
Async await 绝对可以帮到你。当您有 CPU 绑定工作要异步执行时,您可以使用 Task.Run()
。这个方法可以"awaited"这样代码会在任务完成后继续。
对于你的情况,我会这样做:
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]);
}