Sponsor's Renewal function stops being called - vb.net

I have a server and client process both running on the same machine. The client creates a CAO object and uses it for some time (<1s up to hours). It takes a lot of memory so I want to dispose of this object as soon as possible after the client finishes with it.
I set InitialLeaseTime and RenewOnCallTime to 10s (0.1s and 15s have the same problem). I can see that for a few minutes, the sponsor's Renweal functon is being called every 10s. After several minutes the client starts doing different kind of work and the sponsor stops being called (this seems wrong). A few minutes later when the client tries to use the remote object, it throws an exception saying it has been disconnected (probably because the sponsor wasn't called for a long time).
It seems like the lease manager somehow stops trying to check the lease after a while.

Long time in-between responses, but I figure others may run into this issue too, so here goes.
I'd recommend attaching to your server in VS, going to the Debug menu, choosing 'exceptions,' and then checking the 'System.Net.Sockets.SocketException' exception. This will break your program on any socket exception that occurs.
In my case, I've recently begun seeing this issue, and after a lot of debugging noticed that just before the Lease Manager stops checking for leases, a SocketException was occurring. In my case, the socket exception was AddressChangedCallback, with the stack trace:
1 [External Code]
2 System.dll!System.Net.Dns.TryGetAddrInfo(string name = "me.win.mycompany.com", System.Net.AddressInfoHints flags, out System.Net.IPHostEntry hostinfo = null)
3 System.dll!System.Net.Dns.GetAddrInfo(string name)
4 System.dll!System.Net.Dns.InternalGetHostByName(string hostName, bool includeIPv6)
5 System.dll!System.Net.Dns.GetHostEntry(string hostNameOrAddress)
6 System.Runtime.Remoting.dll!System.Runtime.Remoting.Channels.CoreChannel.UpdateCachedIPAddresses()
7 System.Runtime.Remoting.dll!System.Runtime.Remoting.Channels.CoreChannel.OnNetworkAddressChanged(object sender = null, System.EventArgs e = {System.EventArgs})
8 mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx)
9 mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx)
10 mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state)
11 System.dll!System.Net.NetworkInformation.NetworkChange.AddressChangeListener.AddressChangedCallback(object stateObject, bool signaled)
12 mscorlib.dll!System.Threading._ThreadPoolWaitOrTimerCallback.PerformWaitOrTimerCallback(object state, bool timedOut)
13 [External Code]
This AddressChangedCallback, which, in my case, seems to be related to a network adapter going down or being changed (you can see your network adapters by holding windows+r then typing ncpa.cpl - if you have two or more it's possible this event is caused by you switching between them) appeared to cause the socket to stop reading. This meant that the next time the LeaseManager went to use the remoting connection to check the remote lease, it couldn't read that lease from the dead socket. So, it did the reasonable thing - disconnect that sponsor, since we can't read it anymore, and remove it from the list of sponsors for the object. And since it's probably the only sponsor for the object in question, that object then gets unsponsored by the LeaseManger, leaving it free for the GC to eventually pick up.
One approach to solving this is to, in your InitializeLifetimeService() method, return null instead of setting timeouts. This bypasses the LeaseManager, so you never have to worry about the object getting de-sponsored due to a socket exception, since you're not using leases in the first place. However, if you're like me, this also means you could have a buildup of objects and unmanaged resources over a period of time on the server. The only way around the buildup issue that I can see is making your remoting object implement Dispose, and making sure that you Dispose it when you're finished with it. Basically, you can't rely on the LeaseManager handling garbage collection, so you'll have to do GC yourself, the ol' fashioned way.
Also worthy of note: the ITrackingHandler object will allow you to track when LeaseManager-related objects are Disconnected, Marshaled, and Unmarshaled. It was a big help in figuring out what was going on, since I could see that an object was being disconnected, instead of inferring it from the fact that the calls stopped happening.

I've worked around it by putting the sponsor on the server instead of the client. The server side sponsor seems to be reliably called enough to keep the remote object alive.
Class SelfSponsor
Implements ISponsor
Public Function Renewal(ByVal lease As ILease) As System.TimeSpan Implements ISponsor.Renewal
Return lease.RenewOnCallTime
End Function
End Class
And in the class of the MarshalByRef remote object:
Private Sponsor As SelfSponsor
Public Sub SponsorYourself()
Sponsor = New SelfSponsor
DirectCast(GetLifetimeService(), ILease).Register(Sponsor)
End Sub
Public Sub UnSponsorYourself()
DirectCast(GetLifetimeService(), ILease).Unregister(Sponsor)
End Sub
Somehow the SponsorYourself() code throws an exception if it's placed in the constructor so the client calls SponsorYourself immediately after creating the object.
This would be a bad solution if the server is always running and clients come and go because if a client exits abnormally without explicitly calling UnsponsorYourself() then the object will stay alive forever. But in my case the server is started and stopped by the client so that doesn't matter.

Related

How to access CAN signals dynamically (by string) in CAPL?

I'm trying to force CAN signals to given values using COM interface of CANalyzer. Since there is no COM method to send CAN messages, I'm implementing a workaround using CAPL:
void SendMySignal(int value) {
message MyMessage msg;
msg.MySignal = value;
output(msg);
}
This works fine, however since MyMessage and MySignal are referenced statically (by name) here, I'll have to implement N functions to be able to send N signals (or an N-way switch statement, etc). Is there a way to avoid the hassle and access signals inside a message by string? Something like this:
void SendSignal(int MessageID, char SignalName, int value)
I'm also open to alternative solutions in case I have missed something in the COM interface. If there is a solution which only works for CANoe, I can ask my boss for a license, but of course I'd prefer to do without.
there is such function, but it is restricted to be used only in test nodes
long setSignal(char signalName[], double aValue);
you can find details in:
CAPL Function Overview » Test Feature Set / Signal Access » SetSignal
Special Use Case: Signal is not known before Measurement Start
and take care about not to send for each signal a new message to avoid bus over-flooding. In my opinion it is a better style to set all signals for whole message and to send it on change only when it is not cyclic. Signal updates in cyclic messages mostly have to be sent in next cycle.

Why does defining a variable of type of Smo.Server cause a 10 second delay

Bear with me here, ok!!
We use SMO a lot to do all kinds of things, including to check for the presence of particular stored procedures in the database. So we have a method in our data access class called HasProc, which returns a boolean. It's in a part of the application that hasn't been changed for over a year, possibly two years.
Lately, it's been taking ages (10s) to return a value, and I've been trying to pin down why.
It turns out that even defining the variable that will hold the SMO Server (not instantiating it, just defining it) causes a 10s delay in the code arriving into the function.
Here's the relevant bit of the code, which just returns True now, for clarity:
Public Function HasProc(ByVal storedProcName As String) As Boolean
Dim s As Microsoft.SqlServer.Management.Smo.Server
Return True
End Function
In Visual Studio 12, stepping through the code using F11, the 10 second delay happens before the code highlight arrives at Public Function etc...
If I comment out the Dim statement, it all runs instantly.
Even more weirdly, if I disable my ethernet adaptor, the delay does not occur.
This is reproducible across three computers. I'm using VS2012, and SMO v11, to which we recently upgraded in order to support SQL Server 2012.
The other thing is that the delay happens even if the Return True statement is before, rather than after the Dim statement.
Any ideas?
This would happen if the static initializer for that class performs network IO (which is generally a bad idea).
If you pause the debugger during the delay, you can find out exactly what it's doing.

Is this a UI-threading issue? Is there an easy way to fix it?

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.

Ada - does pragma Attach_Handler() can attach handler with System.Priority'Last priority?

The next two declarations are equivalent:
protected type prot_Type is
....
pragma Priority(System.Priority'Last);
end;
protected type prot_Type is
....
end;
One way of attaching interrupt handler is:
protected type prot_Type is
procedure Handler;
pragma Attach_Handler(Handler, ...);
end;
--//Attach is made at the creation of the next object:
Object : prot_Type;
it's a legal attachment (It works).
How is it possible that the handler has ceiling priority of System.Priority Last ? (As far as I know the legal priority is in range Priority'Last+1 .. Any_Priority'Last).
Another thing:
if I add the pragma Priority(System.Priority'Last); to the protected declaration, a program_error exception is raised at the elaboration (when attaching the handler).
Someone can please spread the fog?
I finally manage to understand thanks to:
http://www.iuma.ulpgc.es/users/jmiranda/gnat-rts/node33.htm
The fact that an hadler that defined in a protected with ceiling priority System.Priority'Last managed to be attached to Interrupt seems to me like bug in the compiler.
Only hendlers that defined in a protected with ceiling priority in Interrupt_Prioriy'Range can be attached to interrupt.
Another important thing - for non static protected (i.e declared with "protected type ... ") the attachment is made by the creation of the object of that type. The object must be allocated dynamicly.
Yony.
This question is about attaching interrupts (or signals) to a protected object to function as interrupt handlers. It is wonderful that Ada provides you a mostly language-standard way to do this, but there are limits to what is in the standard, and I think your question hits one. You really need to read your compiler's documenation for this one.
For example, if what you are attaching to is an honest-to-god system interrupt, then it is quite possible that your handler will get called directly from the system interrupt, which is of course completely outside of (and thus above) both your OS's process priority and Ada's task priority systems.
Generally in such a case, like with any ISR, you'd want to do the absolute minimum required to make note of and deal with the interrupt, interact with the system as little as possible (no I/O or tasking interactions), and return control back to the system so it can start behaving normally again. In your case, you might want to increment a variable or set a flag internal to your tagged type, take down any volatile info about the interrupt you may need later, then return.

What is the appropriate amount of error-checking?

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.