0

解決方法がわからない論理的な問題があります。基本的に、ユーザーがnumericUpDownボックスで5を選択すると、numericUpDown値に基づいてスレッドを開始するプログラムがあり、5つのスレッドが開始されます。

問題は、ユーザーがスレッドで使用される情報を入力できるリストボックスも持っていることです..

したがって、numericUpDown 値から 5 回ループする代わりに、ループで実行できるようにしたいのは、if; です。ユーザーがlistBoxに10個のアイテムを入力し、5つのスレッドを使用することを選択したとしましょう..次に、すべてのlistBoxアイテムをキューに入れたいが、一度に5つだけ実行したい..

どうすればこれを達成できますか?

ああ、それが重要な場合、これは私がスレッドを開始する方法です:

                Thread thread = new Thread(() => doTask(numeret));
                thread.IsBackground = true;
                thread.Start();
4

3 に答える 3

1

I believe you wish to use a ThreadPool, as explained here:

http://msdn.microsoft.com/en-us/library/system.threading.threadpool.aspx

You need to specify the number of threads to use, and then use ThreadPool.QueueUserWorkItem to queue your tasks.

Alternatively, you can use the parallel extensions to LinQ to perform asynchronous tasks (not the same as multithreading) - and specify the .MaxDegreesOfParalallism() value (which only sets the upper maximum)

itemsToProcess.AsParallel().MaxDegreesOfParalallism(numThreads).ForAll(item =>
{
    doTask(item);
});
于 2012-05-16T15:59:08.933 に答える
0

Usually, something like this is done using worker threads. You create a list of work items (= your listbox entries):

List<WorkItem> myWorkItems = ...; // contains 10 items

And you create your threads. You do not, however, assign a work item to the thread yet (as you do in your example):

for (int i = 0; i < numberOfThreads; i++) {   // creates 5 threads
    var t = new Thread(doWork);
    t.IsBackground = true;
    t.Start();
}

Each thread runs a loop, checking for new work items (thread-safe!) and doing work, until no more work is to be done:

void doWork() {
    while (true) {
        WorkItem item;

        lock(someSharedLockObject) {
            if (myWorkItems.Count == 0)
                break; // no more work to be done
            item = myWorkItems[0];
            myWorkItems.Remove(item);
        }

        doTask(item);
    }
}

This is similar to what the ThreadPool of the .net Framework does. The ThreadPool, however, is designed to work best when the number of threads can be chosen be the Framework. The example above gives you full control over the number of threads (which seems to be what you want).

于 2012-05-16T15:58:28.047 に答える
0

リストボックスからの情報をスタックに保存します (たとえば)。
次に、doTask() メソッドで、スタックから要素をポップし、スタックが空になるまで処理を繰り返します。

基本的 :

//Stack containing the info to process
Stack<string> infos = new Stack<string>();

//Method for the thread
void doTask()
{
    while(true)
    {
        string info;
        //Threadsafe access to the stack
        lock (infos.SyncRoot)
        {
            //Exit the thread if no longer info to process
            if (infos.Count == 0) return;

            info = infos.Pop();
        }
        //Do the actual stuff on the info
        __DoStuff(info);
    }
}
于 2012-05-16T16:08:17.080 に答える