我有一个解析html文档的方法,但是需要很长时间才能解冻UI。所以我想使用一个线程,但我很困惑。有很多种线程,比如背景工作者,调度员等。我应该使用什么类型的线程?另外,在我的方法中,我传递一个参数。如果我使用线程,如何传递一个参数?
答案 0 :(得分:0)
以下是使用后台工作程序的示例代码:
// I usually disable controls (buttons, etc.)
// so user is prevented to perform other
// actions
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += (s, e) =>
{
// Get the parameter
var param = e.Argument as <your expected object>
// Perform parsing
}
worker.RunWorkerCompleted += (s1, e1) =>
{
System.Windows.Threading.Dispatcher.CurrentDispatcher.BeginInvoke(
new Action(() =>
{
// enable you controls here
}));
}
worker.RunWorkerAsync(parameter);
希望这有帮助!
答案 1 :(得分:0)
自WPF以来,我不再使用后台工作者了。我听说它是为WinForms创建的,应该在WPF中避免,但我可能会弄错。 由于您将字符串作为参数传递(而不是某些ui控件),因此访问另一个线程应该没有问题:
private void DoStuff(string documentName)
{
Action a = () =>
{
var result = ParseFile(documentName);
Action b = () =>
{
TextBox1.Text = result;
};
Dispatcher.BeginInvoke(b);
};
a.BeginInvoke(callback =>
{
a.EndInvoke(callback);
}, null);
}
注意:不要将委托放在循环中,而是在委托中放置一个循环。