Monitor.Wait Initially Locked? - c#

Background
I am trying to write an application that does the following:
I make a method call to SomeBlockingMethod.
This method calls blocks until I call SomeUnblockingMethod from another thread.
When SomeUnblockingMethod is called, the routine inside of SomeBlockingMethod will continue.
Note, the first thing I do will be to call the SomeBlockingMethod, and then later on I will call the SomeUnblockingMethod. I am thinking about using a Monitor.Wait/Monitor.Pulse mechanism to achieve this. The only thing is, when one calls Monitor.Wait, you cannot block initally unless the object involved has already been locked by something else (or at least not that I know of)... But, I want blocking to be the first thing I do... So this leads me into my question...
Question
Is there some way I can implement Monitor.Wait to initially block until a call to Monitor.Pulse is made?

You can use AutoResetEvent instead.
AutoResetEvent ar = new AutoResetEvent(false); // false set initial state as not signaled
Then you can use ar.WaitOne() to wait and ar.Set() to signal waiting processes.
You should use Monitor when you want to protect a resource or you have a critical section. If you want to have a signaling mechanism then AutoResetEvent or ManualResetEvent sounds like a better option.

I don't know what is the problem, but what you want is already how it works:
object _lock = new object();
void SomeBlockingMethod()
{
lock(_lock)
Monitor.Wait(_lock);
... // here only after pulse
}
void SomeUnblockingMethod()
{
lock(_lock)
Monitor.Pulse(_lock);
}
Perhaps you are calling SomeBlockingMethod from multiple places, then you want to use PulseAll. Or perhaps SomeUnblockingMethod is called before SomeBlockingMethod?

Related

C# Avoid creation of thread when entering method the second time

say we declare and run a thread in a method which has a while(1) loop. How can one avoid to create and run a second thread when the method is called again?
I only want one thread to start in this method and every time the method is called again, there should be no thread creation all over again. Should I check for the thread name or should I declare the thread as a field of the class?
Any ideas how to do this?
Thanks,
Juergen
It sounds like the thread should indeed be a field of the class - although you'll have to be careful to access it in a thread-safe way, if there could be several threads calling the method to start with.
What do you want to happen the second time - should the method block, or just finish immediately, or perhaps throw an exception? If you don't need to wait for the thread to finish, you might be able to get away with just a flag instead of keeping a reference to the thread itself.
(Note that I've been assuming this is an instance method and you want one extra thread per instance.) If that's not the case, you'll have to adjust accordingly.
Have the method return a singleton, and start the thread in the singleton constructor.
Could you save the synchronization context the first time, check on subsequent times to see if it matches, and post back to it if necessary?
SynchronizationContext syncContext = null;
...
// "object state" is required to be a callback for Post
public void HiThar(object state) {
if (syncContext == null) {
syncContext = SynchronizationContext.Current;
} else {
syncContext.Post(HiThar, state);
}
}

Best practices for moving objects to a separate thread

We have an implementation for an Ultrasound machine application current where the Ultrasound object is created on the UI's thread. A Singleton implementation would have been good here, but regardless, isn't.
Recently, the set methods changed such that they automatically stop and restart the ultrasound machine, which can take between 10-100ms depending on the state of the machine. For most cases, this isn't too bad of a problem, however it's still causing the UI thread to block for 100ms. Additionally, these methods are not thread-safe and must be called on the same thread where the object was initialized.
This largest issue this is now causing is unresponsive buttons in the UI, especially sliders which may try to update variables many times as you slide the bar. As a result, sliders especially will stutter and update very slowly as it makes many set calls through databound propeties.
What is a good way to create a thread specifically for the creation and work for this Ultrasound object, which will persist through the lifetime of the application?
A current temporary workaround involves spawning a Timer, and invoking a parameter update once we have detected the slider hasn't moved for 200ms, however a Timer would then have to be implemented for every slider and seems like a very messy solution which solves unresponsive sliders, but still blocks the UI thread occasionally.
One thing that's really great about programming the GUI is that you don't have to worry about multiple threads mucking things up for you (assuming you've got CheckForIllegalCrossThreadCalls = true, as you should). It's all single-threaded, operating by means of a message pump (queue) that processes incoming messages one-by-one.
Since you've indicated that you need to synchronize method calls that are not written to be thread-safe (totally understandable), there's no reason you can't implement your own message pump to deal with your Ultrasound object.
A naive, very simplistic version might look something like this (the BlockingCollection<T> class is great if you're on .NET 4.0 or have installed Rx extensions; otherwise, you can just use a plain vanilla Queue<T> and do your own locking). Warning: this is just a quick skeleton I've thrown together just now; I make no promises as to its robustness or even correctness.
class MessagePump<T>
{
// In your case you would set this to your Ultrasound object.
// You could just as easily design this class to be "object-agnostic";
// but I think that coupling an instance to a specific object makes it clearer
// what the purpose of the MessagePump<T> is.
private T _obj;
private BlockingCollection<Action<T>> _workItems;
private Thread _thread;
public MessagePump(T obj)
{
_obj = obj;
// Note: the default underlying data store for a BlockingCollection<T>
// is a FIFO ConcurrentQueue<T>, which is what we want.
_workItems = new BlockingCollection<Action<T>>();
_thread = new Thread(ProcessQueue);
_thread.IsBackground = true;
_thread.Start();
}
public void Submit(Action<T> workItem)
{
_workItems.Add(workItem);
}
private void ProcessQueue()
{
for (;;)
{
Action<T> workItem = _workItems.Take();
try
{
workItem(_obj);
}
catch
{
// Put in some exception handling mechanism so that
// this thread is always running. One idea would be to
// raise an event containing the Exception object on a
// threadpool thread. You definitely don't want to raise
// the event from THIS thread, though, since then you
// could hit ANOTHER exception, which would defeat the
// purpose of this catch block.
}
}
}
}
Then what would happen is: every time you want to interact with your Ultrasound object in some way, you do so through this message pump, by calling Submit and passing in some action that works with your Ultrasound object. The Ultrasound object then receives all messages sent to it synchronously (by which I mean, one at a time), while operating on its own non-GUI thread.
You should maintain a dedicated UltraSound thread, which creates the UltraSound object and then listens for callbacks from other threads.
You should maintain a thread-safe queue of delegates and have the UltraSound thread repeatedly execute and remove the first delegate in the queue.
This way, the UI thread can post actions to the queue, which will then be executed asynchronously by the UltraSound thread.
I'm not sure I fully understand the setup, but here is my attempt at a solution:
How about having the event handler for the slider check the last event time, and wait for 50ms before processing a user adjustment (only process the most recent value).
Then have a thread using a while loop and waiting on an AutoResetEvent trigger from the GUI. It would then create the object and set it?

C# Is it possible to interrupt a specific thread inside a ThreadPool?

Suppose that I've queued a work item in a ThreadPool, but the work item blocks if there is no data to process (reading from a BlockingQueue). If the queue is empty and there will be no more work going into the queue, then I must call the Thread.Interrupt method if I want to interrupt the blocking task, but how does one do the same thing with a ThreadPool?
The code might look like this:
void Run()
{
try
{
while(true)
{
blockingQueue.Dequeue();
doSomething();
}
}
finally
{
countDownLatch.Signal();
}
}
I'm aware that the best thing to do in this situation is use a regular Thread, but I'm wondering if there is a ThreadPool equivalent way to interrupt a work item.
Which BlockingQueue is that? Is that a BCL class? TPL class? Or custom?
No matter; simply - I wouldn't. You could do something early in the thread's life to store the thread reference, but I simply wouldn't use the ThreadPool for this job as it sounds like it is longer running. A regular Thread would seem more appropriate.
I'm also surprised that there is no inbuilt method of telling the queue to release all the workers - I've written blocking queues before, and I tend to use the pattern (for example, from here):
public bool TryDequeue(out T value) {...}
with this:
returning true immediately if there is data
blocking and (eventually) returning true if there isn't data but some is added
blocking and (eventually) returning false if the queue is being shut down

C#: Properly freeing thread

I've got an abstract class that spawns an infinitely-looping thread in its constructor. What's the best way to make sure this thread is aborted when the class is done being used?
Should I implement IDisposable and simply this use this?
public void Dispose()
{
this.myThread.Abort();
}
I read that Abort() is evil. Should I instead have Dispose() set a private bool flag that the thread checks for true to exit its loop?
public void Dispose()
{
this.abort = true;
}
// in the thread's loop...
if (this.abort)
{
break;
}
Use the BackgroundWorker class instead?
I would like to expand on the answer provided by "lc" (which is otherwise great).
To use his approach you also need to mark the boolean flag as "volatile". That will introduce a "memory barrier" which will ensure that each time your background thread reads the variable that it will grab it from memory (as opposed to a register), and that when the variable gets written that the data gets transfered between CPU caches.
Instead of having an infinite loop, use a boolean flag that can be set by the main class as the loop condition. When you're done, set the flag so the loop can gracefully exit. If you implement IDisposable, set the flag and wait for the thread to terminate before returning.
You could implement a cancellable BackgroundWorker class, but essentially it will accomplish the same thing.
If you really want, you can give it a window of time to finish itself after sending the signal. If it doesn't terminate, you can abort the thread like Windows does on shutdown.
The reason I believe Thread.Abort is considered "evil" is that it leaves things in an undefined state. Unlike killing an entire process, however, the remaining threads continue to run and could run into problems.
I'd suggest the BackgroundWorker method. It's relatively simple to implement and cleans up well.

Asynchronous Calls Newbie Question

I am working on a small project where I need to make two asynchronous calls right after another.
My code looks something like this:
AsynchronousCall1();
AsynchronousCall2();
The problem I'm having is that both calls take anywhere from one to two seconds to execute and I never know which one will finish last. What I'm looking for is a way to determine who finishes last. If Call1() finishes last, I do one thing. If Call2() finishes last, I do another thing.
This is a simple example of using a lock to ensure that only one thread can enter a piece of code. But it's a general example, which may or may not be best for your application. Add some details to your question to help us find what you're looking for.
void AsynchronousCall1()
{
// do some work
Done("1");
}
void AsynchronousCall2()
{
// do some work
Done("2");
}
readonly object _exclusiveAccess = new object();
volatile bool _alreadyDone = false;
void Done(string who)
{
lock (_exclusiveAccess)
{
if (_alreadyDone)
return;
_alreadyDone = true;
Console.WriteLine(who + " was here first");
}
}
I believe there is a method that is a member of the Thread class to check on a specific thread and determine its status. The other option would be to use a BackgroundWorker instead, as that would allow you to spell out what happens when that thread is finished, by creating seperate methods.
The "thread-unsafe" option would be to use a class variable, and at the end of each thread if it isn't locked / already have the other thread's value, don't set it. Otherwise set it.
Then when in your main method, after the call to wait for all threads to finish, test the class variable.
That will give you your answer as to which thread finished first.
You can do this with two ManualResetEvent objects. The idea is to have the main thread initialize both to unsignaled and then call the asynchronous methods. The main thread then does a WaitAny on both objects. When AsynchronousCall1 completes, it signals one of the objects. When AsynchronousCall2 completes, it signals the other. Here's code:
ManualResetEvent Event1 = new ManualResetEvent(false);
ManualResetEvent Event2 = new ManualResetEvent(false);
void SomeMethod()
{
WaitHandle[] handles = {Event1, Event2};
AsynchronousCall1();
AsynchronousCall2();
int index = WaitHandle.WaitAny(handles);
// if index == 0, then Event1 was signaled.
// if index == 1, then Event2 was signaled.
}
void AsyncProc1()
{
// does its thing and then
Event1.Signal();
}
void AsyncProc2()
{
// does its thing and then
Event2.Signal();
}
There are a couple of caveats here. If both asynchronous methods finish before the call to WaitAny, it will be impossible to say which completed first. Also, if both methods complete very close to one another (i.e. call 1 completes, then call 2 completes before the main thread's wait is released), it's impossible to say which one finished first.
You may want to check out the Blackboard design pattern: http://chat.carleton.ca/~narthorn/project/patterns/BlackboardPattern-display.html. That pattern sets up a common data store and then lets agents (who know nothing about one another -- in this case, your async calls) report their results in that common location. Your blackboard's 'supervisor' would then be aware of which call finished first and could direct your program accordingly.

Categories