本文介绍了从任务并行库更新进度UI对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
基本上我想更新的FormMain(WindowsForm)进度UI对象。我使用.NET 4.0
下面是在Form1.designer.cs代码
命名空间ProgressBarApp
{
公共部分Form1类:表格
{
私人System.Windows.Forms.ProgressBar curProgressBar;
公共Form1中()
{
的InitializeComponent();
}
私人无效Form1_Load的(对象发件人,EventArgs五)
{
CustomProcess theProcess =新CustomProcess();
theProcess.Process();
}
}
}
下面是CustomProcess的定义的.cs
命名空间ProgressBarApp
{
类CustomProcess
{
公共无效流程()
{
的for(int i = 0;我小于10;我++)
{
任务ProcessATask = Task.Factory.StartNew(()=>
{
Thread.sleep代码(1000); //模拟过程
}
);
任务UpdateProgressBar = ProcessATask.ContinueWith((前身)=>
{?
//如何更新UI时进度条对象这里
$} b $ b);
}
}
}
}
解决方案
您可以使用来做到这一点。要使用它的工作
,你需要创建一个的TaskScheduler
,您可以通过调用的
任务UpdateProgressBar = ProcessATask.ContinueWith(前提= GT;
{
//你可以更新这里,进度条对象
},TaskScheduler.FromCurrentSynchronizationContext());
如果你调用此功能才能进程()$ C $ ç直接从UI线程>。
Basically i would like to update ProgressBar UI object on the FormMain (WindowsForm). I am using .NET 4.0
Here are the code in the Form1.Designer.cs
namespace ProgressBarApp
{
public partial class Form1 : Form
{
private System.Windows.Forms.ProgressBar curProgressBar;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
CustomProcess theProcess = new CustomProcess();
theProcess.Process();
}
}
}
Here is the definition of CustomProcess.cs
namespace ProgressBarApp
{
class CustomProcess
{
public void Process()
{
for (int i = 0; i < 10; i++)
{
Task ProcessATask = Task.Factory.StartNew(() =>
{
Thread.Sleep(1000); // simulating a process
}
);
Task UpdateProgressBar = ProcessATask.ContinueWith((antecedent) =>
{
// how do i update the progress bar object at UI here ?
}
);
}
}
}
}
解决方案
You can use SynchronizationContext
to do this. To use it for a Task
, you need to create a TaskScheduler
, which you can do by calling TaskScheduler.FromCurrentSynchronizationContext
:
Task UpdateProgressBar = ProcessATask.ContinueWith(antecedent =>
{
// you can update the progress bar object here
}, TaskScheduler.FromCurrentSynchronizationContext());
This will work only if you call Process()
directly from the UI thread.
这篇关于从任务并行库更新进度UI对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!