Why do I never get the ObjectDisposedException? - dispose

My test method looks like this:
private static System.Timers.Timer _myTimer;
static void Main(string[] args)
{
using (_myTimer = new System.Timers.Timer(1000))
{
_myTimer.Elapsed += (o, e) => Console.WriteLine($"timer elapsed");
_myTimer.AutoReset = true;
_myTimer.Enabled = true;
Thread.Sleep(4000); // let the timer fire a couple of times
} // dispose timer?
Thread.Sleep(2000); // timer won't fire here
try
{
Console.WriteLine($"no problem accessing _myTimer: {_myTimer.Interval}"); // this won't throw an ObjectDisposedException on _myTimer
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex}");
}
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
try
{
Console.WriteLine($"no problem accessing _myTimer: {_myTimer.Interval}"); // still no ObjectDisposedException
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex}");
}
try
{
//_myTimer.Start(); // throws the ObjectDisposedException
_myTimer.Dispose(); // does not throw the ObjectDisposedException
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex}");
}
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
try
{
Console.WriteLine($"no problem accessing _myTimer: {_myTimer.Interval}"); // still no ObjectDisposedException
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex}");
}
Console.WriteLine("Press any key to continue...");
Console.ReadLine();
}
I would expect to get the ObjectDisposedException after leaving the using block.
Accessing the _myTimer.Interval works all the way to the end of the program. Also, I can call _myTimer.Dispose() anytime. Even waiting for the GarbageCollector does not help to get the ObjectDisposedException.
However, I do get the ObjectDisposedException if I call _myTimer.Start() after leaving the using block.
How can _myTimer be around for the entire lifetime of my program?

Calling Dispose doesn't remove the object or references to it. It will not be GCed as long as there are references to it. Dispose releases unmanaged resources within the object, which is likely but by no means guaranteed to cause at least some of its methods to stop working and start throwing ObjectDisposedException.

Related

Finding all methods that hasn't log inside try catch with NDepend

I'm refactoring an existing application and I have got a per class instance in the form
private readonly ILog log; //(Log4net, but the namespace isn't
I've got some method in the form
public List<Nofity> GetXXX(string codice)
{
try
{
[code]
}
catch (Exception ex)
{
throw ex;
}
}
I need to find the methods that haven't got
catch (Exception ex)
{
log.Error(ex);
throw ex;
}
Is it possible with NDepend?
I also wish to find all the try catch method that swallow the exception
catch()
{
}
How can I do that?
Thanks

How can I throw an exception within ListeningExecutorService?

I used ListeningExecutorService of guava in my project, got confused about the exception handling.
I used a thread pool, submit a task to it, and set a timeout to the listenableFuture, and add a callback to it.
final ListeningExecutorService threadPool = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
Futures.addCallback(listenableFuture, new FutureCallback<**>() {
#Override
public void onSuccess(#Nullable ** data) {
xxxxxxx;
}
public void onFailure(Throwable t) {
xxxxxxxxxx;
if (t instanceof CancellationException) {
throw new QueryException("yyyy");
} else {
throw new QueryException("zzzzz");
}
}
});
I can't catch the exception inside the callback. So I use another ListenableFuture to get the exception
ListenableFuture allFutures = Futures.allAsList(allFuturesList);
try {
allFutures.get();
} catch (CancellationException ce) {
throw new QueryException("");
} catch (InterruptedException t) {
throw new QueryException("");
} catch (ExecutionException e) {
Throwable t = e.getCause();
if (t instanceof QueryException)
throw (QueryException) t;
else
throw new QueryException();
} catch (QueryException qe) {
throw qe;
} catch (Exception e) {
throw new QueryException();
} finally {
}
But I when the callback throw a QueryException, the allFutures can't catch it, allFutures can only catch a CancellationException without the detail error message.
How can I get my detail error message?
Futures.allAsList doesn't do what you expect it to do
From the Javadoc: (emphasis is from me)
Canceling this future will attempt to cancel all the component futures, and if any of the provided futures fails or is canceled, this one is, too.
What you should probably do is create your own aggregating future. You can base your code on Guava's own internal mechanism. See the source code for more info.
Anyways, do not throw exceptions in your FutureCallback::onFailure method.

How to get Parrot AR.Drone 2.0 fly? State Error occurred

I am trying to implement javadrone (AR.Drone Java API) in my project. However, it was occurred state changed error when I compile my java code and try to fly it. I was able to send command to AR.Drone and fly for the first time. After successfully take off for the first time,it won't take off again due to "state changed" error. I have no idea what went wrong in my code. Please help me out. Thanks! There are 3 files that are required in this project. My java file(arDroneFrame.java),NavData.java(from javadrone), and ARDrone.java(from javadrone).The The main java file: arDroneFrame.java. When I press the TakeOff button, it should make AR.Drone fly and land afterwards.
In my arDroneFrame.java,
private void jButtonTakeOffActionPerformed(java.awt.event.ActionEvent evt) {
com.codeminders.ardrone.ARDrone drone;
try{
drone = new com.codeminders.ardrone.ARDrone();
drone.connect();
drone.clearEmergencySignal();
// Wait until drone is ready
drone.waitForReady(CONNECT_TIMEOUT);
// do TRIM operation
drone.trim();
// Take off
System.err.println("Taking off");
drone.takeOff();
// Fly a little :)
Thread.sleep(5000);
//Land
System.err.println("Landing");
drone.land();
// Give it some time to land
Thread.sleep(2000);
// Disconnect from the done
drone.disconnect();
} catch (UnknownHostException ex) {
Logger.getLogger(arDroneFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(arDroneFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (InterruptedException ex) {
Logger.getLogger(arDroneFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
In ARDrone.java, I had commented out some java coding.This is because only when I comment out those java code, it can only works. If I uncomment them, my program will be stuck there (no respond at all).
public void waitForReady(long how_long) throws IOException
{
/*long since = System.currentTimeMillis();
synchronized(state_mutex)
{
while(true)
{
if((System.currentTimeMillis() - since) >= how_long)
{
try
{
disconnect();
} catch(IOException e)
{
}
// Timeout, too late
throw new IOException("Timeout connecting to ARDrone");
} else if(state == State.DEMO)
{
return; // OK! We are now connected
} else if(state == State.ERROR || state == State.DISCONNECTED)
{
throw new IOException("Connection Error");
}
long p = Math.min(how_long - (System.currentTimeMillis() - since), how_long);
if(p > 0)
{
try
{
state_mutex.wait(p);
} catch(InterruptedException e)
{
// Ignore
}
}
}
}*/
while(state == State.DEMO)
{
System.out.println("Changed to DEMO !");
return; // OK! We are now connected
}
}
Program Output:
126 [Thread-7] DEBUG ardrone.ARDrone - State changed from TAKING_OFF to ERROR with exception
java.lang.NullPointerException
at com.codeminders.ardrone.NavData$FlyingState.fromControlState(NavData.java:58)
at com.codeminders.ardrone.NavData.getFlyingState(NavData.java:622)
at com.codeminders.ardrone.ARDrone.navDataReceived(ARDrone.java:431)
at com.codeminders.ardrone.NavDataReader.run(NavDataReader.java:92)
at java.lang.Thread.run(Thread.java:745)

Hibernate Search call to SearchFactory optimize does not invoke immediately

I'm trying to call SearchFactory optimize to run a scheduled index maintenance job (compacting segments - the application is a write intensive). But it does not seem to invoke immediately until I shutdown the Tomcat. My code is calling simply like this.
public synchronized void optimizeIndexes() {
getFullTextEntityManager().flushToIndexes(); //apply any changes before optimizing
getFullTextEntityManager().getSearchFactory().optimize();
logger.info("[Lucene] optimization has performed on all the indexes...");
}
I got it to work around by loaning IndexWriter from HSearch backend.
private synchronized void optimizeBareMetal() {
try {
LuceneBackendQueueProcessor backend = (LuceneBackendQueueProcessor) getIndexManager().getBackendQueueProcessor();
LuceneBackendResources resources = backend.getIndexResources();
AbstractWorkspaceImpl workspace = resources.getWorkspace();
IndexWriter indexWriter = workspace.getIndexWriter();
indexWriter.forceMerge(1, true);
indexWriter.commit();
} catch (LockObtainFailedException e) {
e.printStackTrace();
} catch (CorruptIndexException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private synchronized DirectoryBasedIndexManager getIndexManager() {
SearchFactoryImplementor searchFactory = (SearchFactoryImplementor) getFullTextEntityManager().getSearchFactory();
IndexManagerHolder indexManagerHolder = searchFactory.getIndexManagerHolder();
return (DirectoryBasedIndexManager) indexManagerHolder.getIndexManager(getEntityClass().getName());
}

C Sharp GUI/Socket Crashing on GUI Update

Whenever handleResponse calls the delegate function "func" my GUI crashes with no exception. The delegate function appends text to a RichTextBox on the GUI.
If I call this.func in "connect" it works just fine.
private void handleResponse(IAsyncResult result)
{
try
{
this.func.Invoke("test");
}
catch (Exception e)
{
throw e;
}
}
public void connect(string ip, int port, delegateFunction func) {
try
{
connection.Connect(ip, port);
socket = connection.Client;
this.func = func;
socket.BeginReceive(incomingBuffer, 0, incomingBuffer.Length, SocketFlags.None, handleResponse, null);
}
catch (Exception e)
{
throw e;
}
}
Could be a threading issue. Your GUI probably has to be updated on a specific GUI thread. How switching to that thread is achieved is specific to the GUI framework you use.