问题
I want to create a WPF application that does this: The application will have 8 Tasks running together. Each task will be able to ad some strings to a text box shown in the main window.
how do I get the tasks all running at the same time, and running on the main UI Thread?
(30/04/13:)
please see the next code:
private void RunTasks(int ThreadsNumber)
{
int Ratio = NumbersToCheck / ThreadsNumber;
for (int i = 0; i < ThreadsNumber; i++)
{
Task.Run(() =>
{
int counter = 0;
int low = Ratio * i;
int high = Ratio * (i + 1);
Dispatcher.Invoke(DispatcherPriority.Normal,
(Action)(() =>
{
for (int j = low; j < high; j++)
{
if(IsPrime(j))
MessageList.Items.Add(j);
}
}));
});
}
}
MessageList is a listbox. how come when I run this code, id don't see the smallest prime numbers added to this listbox? (3,5,7,11 and so on).
回答1:
Use the Dispatcher to invoke code on the UI thread from your async running one:
// The Work to perform on another thread
Task.Run(()=>
{
// long running operation...
// Sets the Text on a Text Control from the Dispatcher
// so it will access the UI from the UI-Thread
Dispatcher.Invoke(DispatcherPriority.Normal,
(Action)(() => { myText.Text = "From other thread!"; }));
});
来源:https://stackoverflow.com/questions/16287010/how-to-make-some-tasks-change-my-wpf-controls