在C#中异步运行任务 [英] Run task asynchronously in C#
问题描述
我在WinForms应用程序中运行一些繁重的任务.问题是,它在运行时会冻结UI(UI主线程).
I have some process heavy tasks that run in my WinForms app. The problem is, while its running, it freeze the UI (UI main thread).
我在C#中对线程和委托的工作还不多,这就是为什么我希望有人可以帮助我,如何处理那些繁重的任务而不冻结UI,因此用户不认为应用程序在等待时崩溃了?
I haven't worked that much with threads and delegates in C# yet, and that's why I hope someone could help me to, how to handle those process heavy tasks, without freezing the UI, so the user don't think the app is crashing while waiting?
例如.我通过FrontController
打了一个电话,这很花时间:
Eg. I have a call through my FrontController
, that takes time:
_controller.testExportExcel(wrapper, saveDialog.FileName);
因为它正在创建Excel文件.在应用程序正常工作时,我不会在UI上进行响应.
Since it's creating an Excel file. I won't the app to be responding on the UI while its working.
另一个处理繁重任务的示例可能是:
Another example of a process heavy task could be this:
private void dataGridView_liste_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
if (e.ListChangedType != ListChangedType.ItemDeleted)
{
foreach (DataGridViewRow r in dataGridView_liste.Rows)
{
DataGridViewCellStyle red = dataGridView_liste.DefaultCellStyle.Clone();
red.BackColor = Color.LightGreen;
if (r.Cells["News"].Value != null && (bool)r.Cells["News"].Value == true)
r.DefaultCellStyle = red;
}
}
}
foreach
循环需要时间,并冻结UI.我认为,运行该进程并在完成时自动关闭的异步线程可能很有用.但是它是如何工作的呢?
Where the foreach
loop takes time, and freeze the UI. An async thread running the process and automatically closing when its done, could be useful I think. But how does it work??
推荐答案
How about using a Task (if targetting .net 4)? This is considered as a replacement of the BackgroundWorker class since it supports nesting (parent/child tasks), task continuations, etc.
例如
private void dataGridView_liste_DataBindingComplete(object sender,
DataGridViewBindingCompleteEventArgs e)
{
Task t = Task.Factory.StartNew(() =>
{
// do your processing here - remember to call Invoke or BeginInvoke if
// calling a UI object.
});
t.ContinueWith((Success) =>
{
// callback when task is complete.
}, TaskContinuationOptions.NotOnFaulted);
t.ContinueWith((Fail) =>
{
//log the exception i.e.: Fail.Exception.InnerException);
}, TaskContinuationOptions.OnlyOnFaulted);
}
这篇关于在C#中异步运行任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!