Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am not sure which strategy to adopt...I am focusing on my operation getting completed, but I'd also like to keep performance issues to a min too...there is a method called Execute() which has to wait (run synchronously) until an operation completes. This operation happens on another thread. There are 2 ways to implement the same thing...

By using ManualResetEvent

void Execute()
{
    taskHandle = new ManualResetEvent(false);
    .
    .
    //delegate task to another thread
    .
    .
    taskHandle.WaitOne();
}

OR

By using a simple while construct

void Execute()
{
    .
    .
    //delegate task to another thread
    .
    .
    while (!JobCompleted)
        Thread.Sleep(1000);
}

Which one of the two approaches should I adopt...why?

EDIT:

Q2. What if I just had an empty while contruct? Whats the difference...?

while(!JobCompleted);

EDIT: (something I gathered before)

http://www.yoda.arachsys.com/csharp/threads/waithandles.shtml - This article says manualresets are comparitively slower because they go out of managed code and back in...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
196 views
Welcome To Ask or Share your Answers For Others

1 Answer

Out of curiosity, why ManualResetEvent and not AutoResetEvent? Either way, go with the OS primitive over a sleep-check-sleep approach.

You could also use a Monitor lock (either explicitly through Monitor.Enter and Monitor.Exit, or through a lock block), but the approach should be based upon what you're actually doing; if it's a scenario of "there's only one of these things and I need exclusive access", then use a Monitor lock. If it's "I need to wait until the other thread finishes for reasons other than resource access", then use an AutoResetEvent or ManualResetEvent.

The suggestions to use Thread.Join are good if (and only if)

  1. You have access to the other Thread object
  2. You don't want to execute until the other thread terminates.

If either isn't true (you don't have access, or the other thread won't terminate, it will just signal an "all clear") then Thread.Join isn't viable.

The worst option is

while(!JobCompleted);

As that will tie up the processor with needless checks of the variable without any pause in between them. Yes, it will block your thread until the operation completes, but you'll max out CPU usage (or at least a single core's worth).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...