This is somewhat related to this question, but not quite.
I have two classes, FunctionWrapper and TimerWrapper:
classdef FunctionWrapper < handle
methods
function Fcn(obj)
disp('FunctionWrapper.Fcn was called!');
end
end
end
classdef TimerWrapper < handle
properties
Timer
end
methods
function obj = TimerWrapper(other_object)
obj.Timer = timer;
set(obj.Timer, 'Period', 1);
set(obj.Timer, 'ExecutionMode', 'fixedSpacing');
set(obj.Timer, 'TimerFcn', #(event, data) other_object.Fcn);
end
function start(obj)
start(obj.Timer);
end
function stop(obj)
stop(obj.Timer);
end
function delete(obj)
disp('destructor called!');
delete(obj.Timer);
end
end
end
Say I execute the following code in the Command Window:
>> F = FunctionWrapper;
>> T = TimerWrapper(F);
>> clear T %# T's destructor not called
>> timerfind %# just to verify that no, the destructor was never called
Timer Object: timer-1
Timer Settings
ExecutionMode: fixedSpacing
Period: 1
BusyMode: drop
Running: off
Callbacks
TimerFcn: #(event,data)other_object.Fcn
ErrorFcn: ''
StartFcn: ''
StopFcn: ''
What's going on here? I know that timer objects need to be manually deleted, but I thought that would be dealt with in the destructor for TimerWrapper. Without using Amro's ugly but straightforward workaround to overload the clear command, is there a way to clear T from the workspace? Furthermore, nothing is referring to T, so why does a reference to it exist? (The fact that the destructor is never called implies this fact.) Is this buried in the timer object itself?
If you type t = TimerWrapper; f = functions(t.Timer.TimerFcn); f.workspace(2), you'll see that the workspace of the anonymous function used for the callback contains a reference to the TimerWrapper object itself. So there's a kind of circular reference there which is not picked up by clear.
Given how you've set things up, you can remove T (and its underlying timer object) by calling the destructor explicitly and then calling clear.
T.delete
clear T
The difference between clear and delete is kind of confusing (to me, anyway). As you've found, clear doesn't explicitly call the destructor. It just removes the name T from the workspace. So T, and its underlying timer, still exist at that point. If they contained no references to things that still existed, MATLAB would then remove T properly, including calling its destructor. As it is, since the timer contains a reference (in its callback) to T, which still exists, the timer (and thus T as well) is not deleted.
You can find it (despite not having a name in the workspace) with timerfindall, and if you explicitly delete it yourself using
tmrs = timerfindall;
delete(tmrs);
you'll find that T is now properly gone.
I'm not so sure that this is a bug, although I find it pretty confusing, and the distinction between clear and delete could probably be documented better.
As to a workaround, I don't find it a big pain to explicitly call delete, although it's a bit more of a pain to clean things up if you accidentally call clear. I would think the suggestion in message #5 from the thread you linked to, rather than message #4, would be more general and robust.
I don't think you should overload clear in the way #Amro suggests in the separate thread you linked to: although this may work if you call clear T explicitly, you may still get into trouble if you call clear all, or clear variables. (I haven't tried it just now, but I believe these syntaxes of clear don't even loop over things in the workspace and call clear on each - instead they call the clear method of the internal MATLAB workspace object, and that's going to get confusing fast).
It seems as though this might be because the timer's callback is set to a non-default value. A proposed workaround (see message#4 of the linked thread) is to set the callback function only when the start method is called, then setting it to null when the stop method is called.
Related
I just found out that like C#, VB.NET also has the using keyword.
Until now I thought it didn't have it (stupid of me, I know...) and did stuff like this instead:
With New OleDbConnection(MyConnectionString)
' Do stuff
End With
What are the implications of this compared to doing it with a using statement like this
Using cn as New OleDBConnection(MyConnectionString)
With cn
' Do stuff with cn
End With
End using
UPDATE:
I should add that I am familiar with what the using statement does in that it disposes of the object when the construct is exited.
However, as far as I understand the With New ... construct will have the object mark the object as ready for garbage collection when it goes out of scope.
So my question really is, is the only difference the fact that with using I will release the memory right away, whereas with the With construct it will be released whenever the GC feels like it? Or am I missing something bigger here?
Are there any best practice implications? Should I go and rewrite all the code with I used With New MyDisposableObject() ... End With as Using o as New MyDisposableObject()?
With Statements/Blocks
However, as far as I understand the With New ... construct will have the object mark the object as ready for garbage collection when it goes out of scope.
This is both true and not true. It is true in the sense that all objects are "marked" (purists might quibble with this terminology, but the details are not relevant) as ready for garbage collection when they go out of scope. But then in that sense, it is also not entirely true, as there's nothing special about the With keyword with respect to this behavior. When an object goes out of scope, it is eligible for garbage collection. Period. That's true for method-level scope and it's true for block-level scope (e.g., With, For, Using, etc.).
But that's not why you use With. The reason is that it allows you to set multiple properties in sequence on a deeply-nested object. In other words, assume you have an object on which you want to set a bunch of properties, and you access it this way: MyClass.MemberClass.AnotherMemberClass.Items(0). See all those dots? It can (theoretically) become inefficient to write code that has to work through that series of dots over and over to access the exact same object each time you set a property on it. If you know anything about C or C++ (or any other language that has pointers), you can think of each of those dots as implying a pointer dereference. The With statement basically goes through all of that indirection only once, storing the resulting object in a temporary variable, and allowing you to set properties directly on that object stored in the temporary variable.
Perhaps some code would help make things clearer. Whenever you see a dot, think might be slow!
Assume that you start out with the following code, retrieving object 1 from a deeply-nested Items collection and setting multiple properties on it. See how many times we have to retrieve the object, even though it's exactly the same object every time?
MyClass.MemberClass.AnotherMemberClass.Items(0).Color = Blue
MyClass.MemberClass.AnotherMemberClass.Items(0).Width = 10
MyClass.MemberClass.AnotherMemberClass.Items(0).Height = 5
MyClass.MemberClass.AnotherMemberClass.Items(0).Shape = Circle
MyClass.MemberClass.AnotherMemberClass.Items(0).Texture = Shiny
MyClass.MemberClass.AnotherMemberClass.Items(0).Volume = Loud
Now we modify that code to use a With block:
With MyClass.MemberClass.AnotherMemberClass.Items(0)
.Color = Blue
.Width = 10
.Height = 5
.Shape = Circle
.Texture = Shiny
.Volume = Loud
End With
The effect here, however, is identical to the following code:
Dim tempObj As MyObject = MyClass.MemberClass.AnotherMemberClass.Items(0)
tempObj.Color = Blue
tempObj.Width = 10
tempObj.Height = 5
tempObj.Shape = Circle
tempObj.Texture = Shiny
tempObj.Volume = Loud
Granted, you don't introduce a new scope, so tempObj won't go out of scope (and therefore be eligible for garbage collection) until the higher level scope ends, but that's hardly ever a relevant concern. The performance gain (if any) attaches to both of the latter two code snippets.
The real win of using With blocks nowadays is not performance, but readability. For more thoughts on With, possible performance improvements, stylistic suggestions, and so on, see the answers to this question.
With New?
Adding the New keyword to a With statement has exactly the same effect that we just discussed (creating a local temporary variable to hold the object), except that it's almost an entirely pointless one. If you need to create an object with New, you might as well declare a variable to hold it. You're probably going to need to do something with that object later, like pass it to another method, and you can't do that in a With block.
It seems that the only purpose of With New is that it allows you to avoid an explicit variable declaration, instead causing the compiler to do it implicitly. Call me crazy, but I see no advantage in this.
In fact, I can say that I have honestly never seen any actual code that uses this syntax. The only thing I can find on Google is nonsense like this (and Call is a much better alternative there anyway).
Using Statements/Blocks
Unlike With, Using is incredibly useful and should appear frequently in typical VB.NET code. However, it is very limited in its applicability: it works only with objects whose type implements the IDisposable interface pattern. You can tell this by checking to see whether the object has a Dispose method that you're supposed to call whenever you're finished with it in order to release any unmanaged resources.
That is, by the way, a rule you should always follow when an object has a Dispose method: you should always call it whenever you're finished using the object. If you don't, it's not necessarily the end of the world—the garbage collector might save your bacon—but it's part of the documented contract and always good practice on your part to call Dispose for each object that provides it.
If you try to wrap the creation of an object that doesn't implement IDisposable in a Using block, the compiler will bark at you and generate an error. It doesn't make sense for any other types because its function is essentially equivalent to a Try/Finally block:
Try
' [1: Create/acquire the object]
Dim g As Graphics = myForm.CreateGraphics()
' [2: Use the object]
g.DrawLine(Pens.Blue, 10, 10, 100, 100)
' ... etc.
End Try
Finally
' [3: Ensure that the object gets disposed, no matter what!]
g.Dispose()
End Finally
But that's ugly and becomes rather unwieldy when you start nesting (like if we'd created a Pen object that needed to be disposed as well). Instead, we use Using, which has the same effect:
' [1: Create/acquire the object]
Using g As Graphics = myForm.CreateGraphics()
' [2: Use the object]
g.DrawLine(Pens.Blue, 10, 10, 100, 100)
' ...etc.
End Using ' [3: Ensure that the object gets disposed, no matter what!]
The Using statement works both with objects you are first acquiring (using the New keyword or by calling a method like CreateGraphics), and with objects that you have already created. In both cases, it ensures that the Dispose method gets called, even if an exception gets thrown somewhere inside of the block, which ensures that the object's unmanaged resources get correctly disposed.
It scares me a little bit that you have written code in VB.NET without knowing about the Using statement. You don't use it for the creation of all objects, but it is very important when you're dealing with objects that implement IDisposable. You definitely should go back and re-check your code to ensure that you're using it where appropriate!
By using With...End With, you can perform a series of statements on a specified object without specifying the name of the object multiple times.
A Using block behaves like a Try...Finally construction in which the Try block uses the resources and the Finally block disposes of them.
Managed resources are disposed by the garbage collector without any extra coding on your part.
You do not need Using or With statements.
Sometimes your code requires unmanaged resources. You are responsible for their disposal. A Using block guarantees that the Dispose method on the object is called when your code is finished with them.
The difference is the Using With...End End
Using cn as New OleDBConnection(MyConnectionString)
With cn
' Do stuff with cn
End With
End using
Calls cn.Dispose() automatically when going out of scope (End Using). But in the With New...End
With New OleDbConnection(MyConnectionString)
' Do stuff
End With
.Dispose() is not explicitly called.
Also with the named object, you can create watches and ?cn in the immediate window. With the unnamed object, you cannot.
Using connection... End Using : Be careful !!!
This statement will close your database connection !
In the middle of a module or form(s), i.e.adding or updating records, this will close the connection. When you try to do another operation in that module you will receive a database error. For connections, I no longer use it. You can use the Try... End Try wihthouth the Using statement.
I open the connection upon entry to the module and close it it upon exit. That solves the problem.
I am communicating with a USB-HID device. It will successfully complete hundreds of send-receive requests but occasionally get a Null Exception error.
Is this a threading issue?
FormMain.vb:
myHidDevice.transmitPacket(Packet)
myHidDevice.resetEvent.WaitOne(6)
If myHidDevice.rxDataReady = True then
' Life is good
MyHidDevicePort.vb
Public Sub DataReceivedHandler(ByVal sender as Object, dataReceived as DataReceivedEventArgs)
if dataReceived.data Is Nothing Then
Exit Sub
Else
Dim rDataPacket As List(Of Byte) = dataReceived.data.ToList()
For Each element in rDataPacket
rxData.dataPacket(i) = element
rxDataReady = True
resetEvent.Set()
MySensorClass.vb
Public Overrides Function processPacket(ByRef rxStruct as rStruct, ByVal txPacket()) as Boolean
....
Select Case rxStruct.dataPacket(4)
Case MOD_DISPLAY_SET_BRIGHTNESS
rxData(0) = rxStruct.dataPacket(5)
...
at the rxData.dataPacket(i) = element I will get a NullReference error every now and then. I could enclose it in a try/catch statement, but I'd like to fix the root problem if possible.
This device is communicating to microcontrollers, and it is possible that they won't always give a value... but my feeling is this is some sort of UI threading issue. When debugging, even though there is a null exception, many times there actually does seem to be data in dataReceived.data.ToList(). Is there an easy way to place the whole data processing routine on a thread separate from the UI?
Edit: Changed code to match answer and give more info on where it is used. Still get NullReferenceExceptions after about 1,000 completed send/receive requests to the HID device.
The dialog in the comments is too restricting, so I'll try this as an answer. Unfortunately, there still isn't enough code to give a full answer.
Some sample unknowns:
What is rxData (a custome class, part of the SDK, a struct)?
Where does i come from in the code sample rxData.dataPacket(i) = element, I don't see it decalred or incremented.
Why is the form waiting on myHidDevice.resetEvent.WaitOne(6) and what does it do once it thinks there is sucess?
How/when does processPacket get called?
What I can recommend in general is that access to shared state be wrapped in a SyncLock. And in your case, that includes both rxData and rxDataReady.
In your threaded event callback you need this:
SyncLock(syncRoot)
For Each element in rDataPacket
rxData.dataPacket(i) = element
next
rxDataReady = True
resetEvent.Set()
End SyncLock
And in your Main form where you are waiting for a response you need to wrap access to the ready flag as well:
SyncLock(myHidDevice.syncRoot)
If myHidDevice.rxDataReady = True then
' do something that consumes the data read in the thread
End If
End SyncLock
You have to watch for how long you hold the lock in the read and the write because you cannot be doing both at the same time.
Over all, I wouldn't be surprised if your code code be refactored a bit to make the thread issues easier to deal with. A blocking queue / colletion as you suggested might be a good idea. Just not enough is known of you design/code to give any more concrete advice.
If you know that there is a possibility that your object may be null, placing it inside of a try-catch block would be the incorrect way of handling this situation, as that would be considered coding by exception. Instead, do a null check on your object prior to setting it. e.g.
If Not dataReceived.data Is Nothing Then
Dim rDataPacket As List(Of Byte) = dataReceived.data.ToList()
End If
If your problem lyes with the individual array elements being null, you should also check them to ensure they exist before setting/accessing them.
I have a given line of code, after which none of my own code lines should get executed (not in the same "event loop").
How do I configure the Xcode debugger to catch instances in which some of my own code indeed does get executed after this given line of code?
If it's not possible to filter by the "event loop", can I filter it down to, say, "within 2 seconds after"?
If you wanted to be really convoluted about it, you could rely on knowing that an autorelease pool is drained at the end of the event loop, and create a class which overrides -retain and -release, and when the retain count (which I would recommend an ivar for) hits zero, set a flag, raise the retain count to one again, and somehow get it in the next autorelease pool to be created for the new event loop. At the beginning of each method you want to ensure only happens before some line of code, check that the flag is raised in the class overriding -retain/release, and if it isn't, break/throw error/log/etc. (A macro would probably make shorten the code, and you could conditionally define it for debug builds.) Then, right after the line that you want to ensure none of your code comes after, reset the flag. This way, any code that is entered after this line will see the unset flag and log/fail/tell you about it, and the flag is reset after every event loop.
Some other things: You should either define +retain/+release and add the class object to the autorelease pool with +[NSAutoreleasePool addObject:], or make it a singleton object, seeing as the flag would have to be accessible without really wanting to pass this object around. Second of all, I seem to have neglected how to insert the class/singleton into the autorelease pool for the next loop, after this one is drained. This is because it is the hardest part, and I have no real idea, but I have the feeling [self performSelector:#selector(autorelease) afterDelay:0] would work.
VB.NET has a very handy "with" statement, but it also lets you use it on an unnamed variable, like this:
With New FancyClass()
.Level = "SuperSpiffy"
.Style = Slimming
.Execute()
End With
Is there a way to get at the "hidden" instance, so I can view its properties in the Immediate window? I doubt I'll get it in the watch windows, so immediate is fine.
If you try to access the instance the same way (say, when .Execute() throws an exception) from the Immediate window, you get an error:
? .Style
'With' contexts and statements are not valid in debug windows.
Is there any trick that can be used to get this, or do I have to convert the code to another style? If With functioned more like a Using statement, (e.g. "With v = New FancyClass()") this wouldn't pose a problem.
I know how With is working, what alternatives exist, what the compiler does, etc. I just want to know if this is possible.
As answered, the simple answer is "no".
But isn't another way to do it: instead of declaring and then cleaning up the variable is to use the "Using".
Using fc as new FancyClass()
With fc
.Level = "SuperSpiffy"
.Style = Slimming
.Execute()
End With
End Using
Then you can use fc in the immediate window and don't have to remember to write a
fc=nothing
line.
Just some more thoughts on it ;)
What's wrong with defining a variable on one line and using it in a with-statement on the next? I realise it keeps the variable alive longer but is that so appalling?
Dim x = new SomethingOrOther()
With x
.DoSomething()
End With
x = Nothing ' for the memory conscious
Two extra lines wont kill you =)
Edit: If you're just looking for a yes/no, I'd have to say: No.
I hope there really isn't a way to get at it, since the easy answer is "no", and I haven't found a way yet either. Either way, nothing said so far really has a rationale for being "no", just that no one has =) It's just one of those things you figure the vb debugger team would have put in, considering how classic "with" is =)
Anyway, I know all about usings and Idisposable, I know how to fix the code, as some would call it, but I might not always want to.
As for Using, I don't like implementing IDisposable on my classes just to gain a bit of sugar.
What we really need is a "With var = New FancyClass()", but that might just be confusing!
You're creating a variable either way - in the first case (your example) the compiler is creating an implicit variable that you aren't allowed to really get to, and the in the second case (another answer, by Oli) you'd be creating the variable explicitly.
If you create it explicitly you can use it in the immediate window, and you can explicitly destroy it when you're through with it (I'm one of the memory conscious, I guess!), instead of leaving those clean up details to the magic processes. I don't think there is any way to get at an implicit variable in the immediate window. (and I don't trust the magic processes, either. I never use multiple-dot notation or implicit variables for this reason)
public void PublicMethod(FooBar fooBar)
{
if (fooBar == null)
throw new ArgumentNullException("fooBar", "fooBar cannot be null");
// log the call [added: Thanks S.Lott]
_logger.Log("PublicMethod called with fooBar class " + fooBar.Classification);
int action = DetermineAction();
PrivateMethod(fooBar, action);
}
private void PrivateMethod(FooBar fooBar, int action)
{
if (fooBar == null)
throw new ArgumentNullException("fooBar", "fooBar cannot be null"); // Is this line superfluous?
/*
Do something
*/
}
Is it OK to skip this kind of error checking in private methods if the input is already checked on the public interface? Usually there's some sort of rule-of-thumb one can go by...
Edit:
Maybe ArgumentNullException isn't such a good example because the argument can be made that you should check at both levels but return different error messages.
I would say no.
While it certainly holds true that you in this case knows that it has already been checked for nullability, in two months time the youngest intern will come along and write
PublicMethod2 that also calls PrivateMethod, but lo and behold he forgot to check for null.
Since the public method doesn't really use foobar, I'm not sure why it's checking. The current private method cares, but it's the private method's responsibility to care. Indeed, the whole point of a private method is to delegate all the responsibilities to it.
A method checks the input it actually uses; it doesn't check stuff it's just passing through.
If a different subclass has the same public method, but some different private method implementation -- one that can tolerate nulls -- what now? You have a public method that now has wrong constraints for the new subclass.
You want to do as little as possible in the public method so that various private implementations are free to do the right thing. Don't "over-check" or "just-in-case" check. Delegate responsibility.
I'd error check everything you can, you never know when something might happen that you didn't think about. (and its better safe than sorry)
When using design by contract (http://en.wikipedia.org/wiki/Design_by_contract) it’s normally client’s (public method) responsibility to make correct invocation, i.e. pass on valid parameters. In this particular scenario it depends whether null belongs to a set of valid input values, therefore there are 3 options:
1) Null is valid value: throwing exceptions or errors would have meant breaking the contract, the server (private method) has to process the null and shouldn’t complain.
2) Null is invalid value and passed by code within your control: it is up to the server (private method) to decide how to react. Obviously, throwing an exception is more graceful way of handling the situation, but it has a cost of having to handle that exception somewhere else up the stack. Exceptions are not the best way to deal with violation of contract caused by programming blunders. You really should throw exceptions not when a contract is already violated but when it cannot be fulfilled because of environmental problems what cannot be controlled in software. Blunders are better handled by sticking an assertion into the beginning of the private method to check that the parameter is not null. This will keep the complexity of your code down, there is no cost of having to handle the exception up the stack and it will achieve the goal of highlighting broken contracts during testing.
3) Then there is defensive programming (http://en.wikipedia.org/wiki/Defensive_programming). When dealing with parameters passed by an external code outside your control the immediate layer of your code needs to run paranoid level of checks and return errors according to its communication contract with the external world. Then, going deeper into the code layers not exposed externally, it still makes more sense to stick to the programming by contract.
At least put a comment that PrivateMethod must have a non-null FooBar and that PublicMethod checks this.
You might want to also mark the "private" method as private or protected.
That depends if a null-value indicates an error for a method. Remember that methods could also be called messages to an object; they operate on the state of the object aswell. Parameters can specialize the kind of message sent.
If publicMethod() does not use a parameter and changes the state of the instance while privateMethod() uses the parameter, do not consider it an error in publicMethod, but do in privateMethod().
If publicMethod() does not change state, consider it an error.
You could see the latter case as providing an interface to the internal functioning of an object.
I'd consider the answer to be "yes, do the check again" because:-
The private member could be reused again in the future from a different path through the code, so program defensively against that situation.
If you perform unit tests on private methods
My view might change if I had a static analyser that could pick this up and not flag the potential use of a null reference in the private method.
In cases where PrivateMethod will be called frequently with input that has already been verified, and only rarely with user input, Then I would use the PublicMethod/PrivateMethod concept with no error checking on PrivateMethod (and with PublicMethod doing nothing other then checking the parameters and calling PrivateMethod)
I would also call the private method something like PublicMethod_impl (for "implementation") so it's clear that it's an internal use/ no checking method.
I maintain that this design leads to more robust application, as it forces you to think about what's checked when. Too often people who always check parameters fall into the trap of "I've checked something, therefore I've checked everything".
As an example of this, a former co-worker (programming in C) would, before using a pointer, always check to see if it was null. Generally, the pointers in his code were initialized as startup and never changed, so the chances of it being null were quite low. Moreover, the pointer has one correct value and 65535 possible wrong values, and he was only checking for one of those wrong values.