Run few thread from another thread
I'm starting a backgroundworked on some event. I'm wondering if it is possible: When i'm starting worker, Can i start within this thread some new threads? If it possible, how it affects for performance? In my app I have three threads now, but I want permit one thread to make about 60 new threads. Why 60? I have 60 complicated co开发者_开发问答ntrols, and I want to try to take control from them to one thread per control.
Regards, Greg
It is possible to start many threads from one thread. But if by controls you mean UI controls, I think you need to be in the main UI thread to be able to actually update the controls.
Now, the threads might be able to modify some data that the main UI thread will then apply to the controls, but be careful about the synchronisation, it could get really messy.
As for the performances, threads imply overhead, so depending on your application, it might also make sense to have only one thread dealing with the data for the 60 controls in the background, and have the UI thread update the controls. But that really depends on your application and the way the data is obtained and handled in the background.
As previously stated if you need to implement 60 threads just to manage your UI controls then its very likely that there's something wrong with your design.
However when determining the number of threads you need to consider factors like contention and locking mechanisms. For example if all your threads are using shared data with a lot of reads & few writes then you should consider using ReaderWriterLockSlim to manage access (note don't use the heavyweight ReaderWriterLock class under any circumstances). Alternatively depending on your design semaphores or non-blocking syncronisation methods may be useful here.
In WPF if you need to access to access a UI control from a background thread then you can use Dispatcher as shown below:
private void AddTbToStackPanel(string text)
{
Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() =>
{
StackPanel stackPanel = stackPanel1 as StackPanel;
TextBlock tb = new TextBlock();
tb.Text = text;
stackPanel.Children.Add(tb);
}));
}
精彩评论