Waiting for background thread to complete

Sorry if this is a duplicate, but I'm not quite sure what terms I need to use to find existing answers to this question.

I am trying to improve the initial performance of the application, the pseudocode looks something like this.

LoadBigFileFromDisk();  //slow
SetupNetwork();         //even slower
UseBigFileFromDisk();

I realized that since the first step is disk-related and the other is network-related (and slower), I could run the first in the background thread (currently playing with ThreadPool.QueueUserWorkItem, but not sure if this is the best way) and improve performance a bit .

This works, but it bothers me that I rely on the second step, slow enough for the first completion.

I know that I could install _doneboolean somewhere and while !, but is there a more elegant / idiomatic solution?

(Not.Net 4.0 is all the same, therefore, although I am interested in a task-based task, I need solutions to return).

+5
source share
3 answers

In the "main class", do the following:

ManualResetEvent mre = new ManualResetEvent(false);

in your "main" method do the following:

// Launch the tasks

mre.WaitOne();

in the task when it ends (immediately before returning :-))

mre.Set();

If you need to wait for several events, in your "main" create several ManualResetEventand place them in an array, each event is "connected" to one of the tasks, and then each task is Setits event when it ends. Then in your "main" you do:

WaitHandle.WaitAll(arrayOfManualResetEvents);

, 64 . , ( , , STA, , WinForm).

ManualResetEvent mre = new ManualResetEvent(false);
int remaining = xxx; // Number of "tasks" that must be executed.

// Launch tasks

mre.WaitOne();

if (Interlocked.Decrement(ref remaining) == 0)
{
    mre.Set();
}

0 mre.Set().

+2

:

var loadTask=Task.Factory.StartNew(()=>LoadBigFileFromDisk());
var setupTask=Task.Factory.StartNew(()=>SetupNetwork());

Task.WaitAll(loadTask,setupTask);

UseBigFileFromDisk();

.

var loadThread=new Thread(()=>LoadBigFileFromDisk());
var setupThread=new Thread(()=>SetupNetwork());

loadThread.Start();
setupThread.Start();

loadThread.Join();
setupThread.Join();

UseBigFileFromDisk();

.NET 4. , , .

+3
0

All Articles