开发者

Open up a Tab Item on a new thread?

开发者 https://www.devze.com 2023-04-03 06:49 出处:网络
I want to add new TabTtems to my TabControl, but each TabItem must run on it\'s own thread. What would be the best way to achieve this?

I want to add new TabTtems to my TabControl, but each TabItem must run on it's own thread.

What would be the best way to achieve this?

I thought of using the ThreadPool:

ThreadPool.QueueUserWorkItem(new WaitCallback(HandleNewTabItem),sender);

private void HandleNewTabItem(object sender)
{
    //Adding tabs...
}

Is this this correct way of running a TabItem on it's开发者_运维百科 own Thread?

If not, what do you suggest?

EDIT:

The main reason for this is, i have allot of processing going on in my tabs and the user can add more and more tabs... So i need a way to handle all the processing and still keep my UI responsive.


You can't say for sertain, will the ThreadPool use the different thread for each of your tab.

I don't think it suits for your task. Try to use a Task class with TaskFactory:

Task<double>[] taskArray = new Task<double>[]
   {
       Task<double>.Factory.StartNew(() => DoComputation1()),

       // May be written more conveniently like this:
       Task.Factory.StartNew(() => DoComputation2()),
       Task.Factory.StartNew(() => DoComputation3())                
   };

double[] results = new double[taskArray.Length];
for (int i = 0; i < taskArray.Length; i++)
    results[i] = taskArray[i].Result;

UPDATE:

Why do you want to create a single thread for each tab? This operation is very memory consuming, and, if the number of threads is greater than number of cores in system, additional performance hit is being taken because of windows context switching.

This is why I suggest you to use tasks for your application - if numbers of tasks is greater than numbers of cores, your can wait for results by using of ContinueWith method.

About your question from cooment: Yes, your GUI will be responsive, as the tasks are executing with internally calls to the Thread pool object, and your are free to create new tasks by your TaskFactory.


Have a look at this blog post: Multithreaded UI: HostVisual

It describes how to implement your own class that inherits from FrameworkElement and those contents are handled in its own thread.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号