Do until a var is not null [closed] - c#

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Edit a few years on: this was clearly a terrible approach, at the start of me using C#/.NET. Hopefully this question helps another noob with the same "problem".
Is this the best way to approach this scenario?
while(true)
{
if(Main.ActiveForm != null)
{
Main.ActiveForm.Invoke(new MethodInvoker(Main.SomeMethod));
break;
}
}
This is performed on a second thread.

Is this the best way to approach this scenario?
Just to clarify, the scenario is "I have a property of reference type; as soon as the property is not null I wish to invoke one of its methods", and the technique is "spin up another thread, busy-wait until the value is not null, invoke, and stop waiting".
The answer to your question is no, this is not the best way to approach this scenario. This is a terrible way to solve this problem for several reasons.
First, the code is simply wrong. The C# language makes no guarantee that this code works. If it works, then it is working by accident, and it can stop working at any time.
There are three reasons that this code is wrong.
The first reason it is wrong is because of the way threads work on modern operating systems. It is possible that the two threads are each assigned to their own processor. When a processor accesses memory on a modern machine, it does not go out to main memory every time. Rather, it fetches hundreds or thousands of nearby values into a cache the first time you hit an address. From then on, it accesses the local cache rather than taking the expensive bus ride back to main memory. The implications of that should be obvious: if one thread is writing and another thread is reading, then one thread might be writing to one processor cache and the other might be reading from an entirely different processor cache. They can be inconsistent forever if nothing forces them to be consistent, and therefore your loop can run forever even if the property has been set on another thread.
(And the "backwards" case is also possible; if the value of the property is now null, and was set at some time in the past, then it is possible that the second thread is reading the old, stale value and not the fresh null value. It therefore could decide to not wait at all, and invoke the method on a stale value of the property.)
The second reason this code is wrong is because it has a race condition. Suppose someone assigns the property to non-null on thread one, and then thread two reads it as non-null so you enter the body of the "if", and then thread three assigns it back to null, and then thread two reads it as null and crashes.
The third reason this code is wrong is because the compiler -- either the C# compiler or the jitter -- is permitted to "optimize" it so that it stays in the loop forever without doing the test a second time. The optimizer is allowed to analyze the code and realize that after the first time through the loop, if the test fails then nothing in the rest of the loop can cause it to succeed. It is permitted to then skip the test the next time through because it "knows" that it cannot succeed. Remember, the optimizer is permitted to make any optimization that would be invisible in a single-threaded program.
The optimizer does not actually make this optimization (to my knowledge) but it is permitted to, and a future version could do so. The optimizer can and does make similar optimizations in similar situations.
In order to make this code correct there must be a memory barrier in place. The most common technique for introducing a barrier is to make the access "volatile". The memory barrier forces the processor to abandon its cache and go back to main memory, and discourages the compiler from making aggressive optimizations. Of course, properties may not be volatile, and this technique utterly wrecks performance because it eliminates the one of the most important optimizations in modern processors. You might as well be accessing main memory by carrier pigeon, the cost is so onerous compared to hitting the cache.
Second, the code is bad because you are burning an entire processor sitting there in a tight loop checking a property. Imagine a processor is a car. Maybe your business owns four cars. You are taking one of them and driving it around the block non-stop, at high speed, until the mailman arrives. That is a waste of a valuable resource! It will make the entire machine less responsive, on laptops it will chew through battery like there is no tomorrow, it'll create waste heat, it's just bad.
I note however that at least you are marshalling the cross-thread call back to the UI thread, which is correct.
The best way to solve this problem is to not solve it. If you need something to happen when a property becomes non-null, then the best solution is to handle a change event associated with that property.
If you cannot do that then the best solution is to make the action the responsibility of the property. Change the setter so that it does the action when it is set to non-null.
If you can't make it the responsibility of the property, then make it the responsibility of the user who is setting the property. Require that every time the property be set to non-null, that the action be performed.
If you can't do that then the safest way to solve this problem is to NOT spin up another thread. Instead, spin up a timer that signals the main thread every half second or so, and have the timer event handler do the check and perform the action.
Busy-waiting is almost always the wrong solution.

All you need to do is attach an event handler to the Activated event of your form. Add the following inside that form's constructor:
Activated += SomeMethod;
And it will be fired whenever you re-activate the form after previously using another application.
The primary advantage of this approach is that you avoid creating a new thread just to have it sitting around doing a spinwait (using up a lot of CPU cycles).

If you want to use this approach, note that you have a race condition: someone else might set Main.ActiveForm to null between your test and your Invoke() call. That would result in an exception.
Copy the variable locally before doing any tests to make sure that the variable cannot be made null.
while(true)
{
var form = Main.ActiveForm;
if(form != null)
{
form.Invoke(new MethodInvoker(Main.SomeMethod));
break;
}
}

When you use a loop You are waste CPU.
The beter way to do this is use events:
// make event object in some shared place
var ev = new ManualResetEvent(false);
// do when form loaded
ev.Set();
// wait in thread
ev.WaitOne();

use :
while(Main.ActiveForm == null) { }

I would do it like that.
while(Main.ActiveForm == null)
{
//maybe a sleep here ?!
}
Main.ActiveForm.Invoke(new MethodInvoker(Main.SomeMethod));

Related

C# TPL: Invoke method on outer scoped instance

So my title was fairly obscure, here is what I'm worried about. Can I invoke a method on an instance of a class that is declared outside of the block without suffering pitfalls i.e
Are there concurrency issues for code as structured below.
HeavyLifter hl = new HeavyLifter();
var someActionBlock = new ActionBlock<string>(n =>
{
int liftedStuff= hl.DoSomeHeavyLifting(n);
if (liftedStuff> 0)
.....
});
The source of my concerns are below.
The Block may have multiple threads running at the same time, and each of these threads may enter the DoSomeHeavyLifting method. Does each function invocation get its own frame pointer? Should I make sure I don't reference any variables outside of the CountWords scope?
Is there a better way to do this than to instantiate a HeavyLifter in my block?
Any help is greatly appreciated, I'm not too lost, but I know Concurrency is the King of latent errors and corner cases.
Assuming by frame pointer, that you mean stack frame, then yes, each invocation gets it's own stack frame, and associated variables. If parameters to the function are reference types, then all of the parameters will refer to the same object.
Whether or not it's safe to use the same HeavyLifter instance for all invocations depends on whether the DoSomeHeavyLifting method has side effects. That is, whether DoSomeHeavyLifting modifies any of the contents of the HeavyLifter object's state. (or any other referenced objects)
Ultimately whether it is safe to do this depends largely on what DoSomeHeavyLifting does internally. If it's carefully constructed in order to be reentrant then there are no problems calling it the way you have it. If however, DoSomeHeavyLifting modifies the state, or the state is modified as a side effect of any other operation, then the decision would have to be made in the context of the overall architecture how to handle it. For example, do you allow the state change, and enforce atomicity, or do you prevent any state change that affects the operation? Without knowing what the method is actually doing, it's impossible to give any specific advice.
In general when designing for concurrency it's usually best to assume the worst:
If a race condition can happen, it will.
When a race condition happens, you will lose the race in the most complex way your code allows.
Non-atomic state updates will corrupt each other, and leave your object in an undefined state.
If you use a lock there will be a case where you could deadlock.
Something that doesn't ever happen in debug, will always happen in release.

Strange if-statement behavior with zero value double

Would anyone care to explain to me how the value of this.oBalance.QouteBalance is evaluated to be true for being less than zero when it clearly isn't? Please see image below.
Am I missing something fundamental when it comes to comparing doubles in C#??
public double QouteBalance { get; set; }
UpdateBalance_PositionOpenned() is not being called in a loop, but is being called as part of a more complex event driven procedure that runs on the ticks of a timer (order of milliseconds)
EDIT: Pardon the code if it's messy but I couldn't edit it as this was a run-time error after quite a long run-time so was afraid wouldn't be able to recreate it. The Exception message is not correct and just a reminder for myself. The code after the exception is code I forgot to comment out before starting this particular run.
EDIT 2: I am building and running in Release Mode.
EDIT 3: Pardon my ignorance, but it would seem that I am in fact running in a multi-threaded environment since this code is being called as part of a more complex object method that gets executed on the ticks (Events) of a timer. Would it possible to ask the timer to wait until all code inside its event handler has finished before it can tick again?
EDIT 4: Since this has been established to be a multi-threading issue; I will try to give wider context to arrive at an optimized solution.
I have a Timer object, which executes the following on every tick:
Run a background worker to read data from file
When background worker finishes reading data from file, raise an
Event
In the event handler, run object code that calls the method below
(in the image) and other multiple routines, including GUI updates.
I suppose this problem can be avoided by using the timer Tick events to read the from file but changing this will break other parts of my code.
You're accessing shared variables from multiple threads. It's probably a race condition where one thread has thrown the error but by the time the debugger has caught and attached, the variable's value has changed.
You would need to look at implementing synchronizing logic like locking around the shared variables, etc.
Edit: To answer your edit:
You can't really tell the timer to not tick (well you can, but then you're starting and stopping and even after calling Stop you might still receive a few more events depending on how fast they are being dispatched). That said, you could look at Interlocked namespace and use it to set and clear and IsBusy flag. If your tick method fires and sees you're already working, it just sits out that round and waits for a future tick to handle work. I wouldn't say it's a great paradigm but it's an option.
The reason I specify using the Interlocked class versus just using a shared variable against comes down to the fact you're access from multiple threads at once. If you're not using Interlocked, you could get two ticks both checking the value and getting an answer they can proceed before they've flipped the flag to keep others out. You'd hit the same problem.
The more traditional way of synchronizing access to shared data member is with locking but you'll quickly run into problems with the tick events firing too quickly and they'll start to back up on you.
Edit 2: To answer your question about an approach to synchronizing the data with shared variables on multiple threads, it really depends on what you're doing specifically. We have a very small window into what your application is doing so I'm going to piece this together from all the comments and answers in hopes it will inform your design choice.
What follows is pseudo-code. This is based on a question you asked which suggests you don't need to do work on every tick. The tick itself isn't important, it just needs to keep coming in. Based on that premise, we can use a flagging system to check if you're busy.
...
Timer.Start(Handle_Tick)
...
public void Handle_Tick(...)
{
//Check to see if we're already busy. We don't need to "pump" the work if
//we're already processing.
if (IsBusy)
return;
try
{
IsBusy = true;
//Perform your work
}
finally
{
IsBusy = false;
}
}
In this case, IsBusy could be a volatile bool, it could be accessed with Interlocked namespace methods, it could be a locking, etc. What you choose is up to you.
If this premise is incorrect and you do in fact have to do work with every tick of the timer, this won't work for you. You're throwing away ticks that come in when you're busy. You'd need to implement a synchronized queue if you wanted to keep hold of every tick that came in. If your frequency is high, you'll have to be careful as you'll eventually overflow.
This isn't really an answer but:
UpdateBalance_PositionOpenned() is not being called in a loop, but is
being called as part of a more complex event driven procedure that
runs on the ticks of a timer (order of milliseconds)
see:
Multi-threading? – abatishchev 30 mins ago
Tight timer driven event-loop on the order of milliseconds probably has all the problems of threads, and will be almost entirely impossible to trouble-shoot with a step-through debugger. Stuff is happening way faster than you can hit 'F10'. Not to mention, you're accessing a variable from a different thread each event cycle, but there's no synchronization in sight.
Not really a full answer but too much for a comment
This is how I could code defensively
Local scope leads to less unexpected stuff
And it make code easier to debug and test
public void updateBalance(double amount, double fee, out double balance)
{
try
{
balance = amount * (1.0 + fee);
if (balance < 0.0) balance = 0.0;
}
catch (Exception Ex)
{
System.Diagnostics.Debug.WriteLine(Ex.Message);
throw Ex;
}
}
Value type is copied so even if then input variable for amount changed while the method was executing the value for amount in the method would not.
Now the out balance without locks is a different story.

Why do we need the directly call in a thread-safe call block?

Refer the thread-safe call tutorial at MSDN, have a look at following statments:
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.textBox1.InvokeRequired) {
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
} else {
this.textBox1.Text = text;
}
Of course, I've used it many times in my codes, and understand a little why to use it.
But I still have some unclear questions about those statements, so anybody help me to find them out, please.
The questions are:
Will the code can run correctly with the statements in the if body only? I tried and seems it just cause the problem if the control is not initialize completely. I don't know is there more problem?
Which the advantage of calling method directly (else body) instance via invoker? Does it save resource (CPU, RAM) or something?
Thanks!
You can of course always call using the Invoker, but:
It usually makes the code more verbose and difficult to read.
It is less efficient as there are several extra layers to contend with (setting up delegates, calling the dispatcher and so on).
If you are sure you'll always be on the GUI thread, you can just ignore the above checks and call directly.
If you always run just the first part of the if statement, it will always be fine, as Invoke already checks if you're on the UI thread.
The reason you don't want to do this is that Invoke has to do a a lot of work to run your method, even if you're already on the right thread. Here's what it has to do (extracted from the source of Control.cs):
Find the marshaling control via an upward traversal of the parent control chain
Check if the control is an ActiveX control and, if so, demand unmanaged code permissions
Work out if the call needs to be invoked asynchronously to avoid potential deadlock
Take a copy of the calling thread's execution context so the same security permissions will be used when the delegate is finally called
Enqueue the method call, then post a message to invoke the method, then wait (if synchronous) until it completes
None of the steps in the second branch are required during a direct call from the UI thread, as all the preconditions are already guaranteed, so it's definitely going to be faster, although to be fair, unless you're updating controls very frequently, you're very unlikely to notice any difference.

How to skip UI update if already updating?

[Sorry that English is not my native language.]
So, I have a UI and 1 worker on another thread, the worker will call the UI to Update() in random frequency,
so there might be a lot of Update() invoked to the UI. But if there are really multple Update(), then only the latest one is meaningful, yet I have no way to skip those in between.
So I want to
"detect if there is an Update() ongoing, if yes, just pend 1 more Update()"
"check if there is already 1 more Update() pending, then there is no need to pend more"
before the Update()
But I am not sure what's the best way to do it. I think surely someone has encountered such problem before. Googling just gives me some unrelated result. So I am looking for some patterns or best practices or search terms or advice or suggestion about this.
Thank you very much
It isn't clear what kind of class library you are using. However, invoking Update() is fundamentally wrong. Painting the UI is a low priority task, it should only be done when nothing more important needs to be taken care of.
The proper thing to do is call Invalidate(). You can call it as many times as you want, it cannot 'backup'. When the UI thread is ready and willing, then it will paint the user interface. If the changes happen faster then the UI thread can keep up with then no harm is done, the intermediary paint just didn't happen.
Which is in general something else you need to take care of. It is pretty easy to shoot the foot and invoke hundreds of times per second. Which is pointless, a human cannot perceive changes that fast. Forty times per second is plenty, it looks as smooth as a movie in cinema. Realistically you should use less.
Seems like you need a queue of Update requests with a length of one.
Produce UpdateRequests to the queue and discard them if the queue is full... then consume them from another thread that actually does the final update invoke to the main thread.
If you always want to guarantee that the value retrieved by the UI thread is the last one pushed, consider a stack structure for the data you're sharing between the UI and background threads. You will still need to put a lock on the shared data to ensure that the UI thread doesn't get a "stale" update.
Here's a reference to the Stack class in C#:
http://msdn.microsoft.com/en-us/library/system.collections.stack.aspx
According to the documentation:
Thread Safety
Public static (Shared
in Visual Basic) members of this type
are thread safe. Any instance members
are not guaranteed to be thread safe.
To guarantee the thread safety of the
Stack, all operations must be done
through the wrapper returned by the
Synchronized method.
Enumerating through a collection is
intrinsically not a thread-safe
procedure. Even when a collection is
synchronized, other threads can still
modify the collection, which causes
the enumerator to throw an exception.
To guarantee thread safety during
enumeration, you can either lock the
collection during the entire
enumeration or catch the exceptions
resulting from changes made by other
threads.
EDIT:
Jorge is right- there is also a Queue class that might be better suited:
http://msdn.microsoft.com/en-us/library/system.collections.queue.aspx

The fastest way to call a method

Reading this article I found several ways to call a method.
Method to call:
public static void SendData(string value) { }
Calls:
delegate void MyDelegate(string value);
//Slow method - NOT RECOMMENDED IN PRODUCTION!
SendData("Update");
// Fast method - STRONGLY RECOMMENDED FOR PRODUCTION!
MyDelegate d = new MyDelegate(SendData);
d.BeginInvoke("Update", null, null);
Is it true? Is it faster?
Action send = () => Send("Update");
send();
Or maybe this?
I need to call a method into a SQL CLR trigger with maximum performance so even small speed increase makes sense.
Which is "faster"?
1) Ask Bob to mow your lawn. Wait until he's done. Then go to the mall.
2) Ask Bob to mow your lawn. Go to the mall while he's mowing your lawn.
The second technique gets you to the mall a lot faster. The price you pay is that you have no idea whether the lawn is going to be mowed by the time you get home or not. With the first technique, you know that when you get home from the mall the lawn will be mowed because you waited until it was before you left in the first place. If your logic depends on knowing that the lawn is mowed by the time you get back then the second technique is wrong.
Now the important bit: Obviously neither technique gets your lawn mowed faster than the other. When you're asking "which is faster?" you have to indicate what operation you're measuring the speed of.
Using a delegate is no faster than directly calling the method (in all reality, creating a delegate and then calling it would be more expensive).
The reason that this is going to seem faster is because directly calling the method blocks the executing thread while the method runs. Your delegate example calls the method asynchronously (using BeginInvoke) so the calling thread continues to execute while the method is executed.
Also, whenever you have a call to BeginInvoke on a delegate you should also have the corresponding EndInvoke, which you're missing in your example:
Is EndInvoke() optional, sort-of optional, or definitely not optional?
and
IanG on Tap: EndInvoke Not Optional
Its a placebo speed improvement from the point of view of when SendData is returning to the caller. BeginInvoke will take a ThreadPool thread and start the method on that thread, then return to caller immediately - the actual work is on another thread. The time it takes to do this work will remain the same regardless of the thread its on. It might improve the responsiveness of your application, depending on the work, but delegates are not faster than direct method calls - as I say, in your situation it seems faster because it returns immediately.
Try this: change BeginInvoke to Invoke - the caller is now blocking, the same as calling SendData normally.
Assuming the code comments are not yours (ie, "RECOMMENDED FOR PRODUCTION") I would fast find the developer responsible and make sure they are aware of Delegate.BeginInvoke and the fact that they are making their app multi-threaded without realising it...
To answer the question, a direct method call is always the fastest way - delegates or reflection incur overhead.
Your best chance to increase performance would be to optimize the code in the method that will be in the SQL CLR stored procedure that the trigger will call. Could you post more information about that?
Note that in the article you cite, the author is talking about WCF calls, notably calls for inserting and updating a database.
The keys points to note in that specific case are:
The work is being done by another machine.
The only information you are getting back is "Success!" (usually) or (occasionally) "Failure" (which the author doesn't seem to care about)
Hence, in that specific case, the background call were better. For general purpose use, direct calls are better.

Categories

Resources