运行多个C#任务异步 [英] Running multiple C# Task Async
问题描述
你好,通常我会做一个后台工作,但我想用C#任务去做,而不是,只是为了了解任务更好。
Hi normally I would do this with a Background Worker, but I would like to do it with C# Task instead, just to understand Task better.
的事情是,我有一类具有以下属性
The thing is that I have a class with the following properties
private int _number1;
public int Number1
{
get { return _number1; }
set { _number1 = value; OnPropertyChanged("Number1");}
}
private int _number2;
public int Number2
{
get { return _number2; }
set { _number2 = value; OnPropertyChanged("Number2");}
}
请注意,我用的是INotifyPropertyChanged的。
Please note that I use the INotifyPropertyChanged.
Number1 = Task<int>.Factory.StartNew(() => GenerateResult()).Result;
Number2 = Task<int>.Factory.StartNew(() => GenerateResult2()).Result;
在GenerateResult和GenerateResult2只是dumme方法,谁睡,然后返回一个数字。
The GenerateResult and GenerateResult2 are just dumme methods, who sleeps and then return a number.
我将如何使这项工作异步?因为现在,GenerateResult2()时GenerateResult()完成首次调用。
How would I make this work Async? Since right now, GenerateResult2() is first called when GenerateResult() is finished.
我需要它能够异步工作,因为我不知道,当每个任务将完成,或者即使它要完成的。
I need it to be able work Async, since I have no idea of when each task is going to finish or even if its going to finish.
推荐答案
在获得结果
属性,有效地等待任务完成。它会在后台线程执行,但你是在等待你的主线程为完成你开始下一个线程之前。
When you get the Result
property, you are effectively waiting for the task to complete. It will execute on a background thread but you are waiting in your main thread for the completion before you start the next thread.
请参见 MSDN文档了解详细信息。
您应该能够刚刚从后台线程分配你的属性:
You should be able to just assign your properties from the background thread:
Task<int>.Factory.StartNew(() => Number1 = GenerateResult());
WPF数据绑定将<一href="http://stackoverflow.com/questions/2354438/mvvm-best-practice-to-pass-dispatcher-to-the-viewmodel/2354674#2354674">take护理编组 PropertyChanged事件到正确的调度线程。
WPF databinding will take care of marshalling the PropertyChanged event to the correct dispatcher thread.
这篇关于运行多个C#任务异步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!