NotSupportedException on generic collection when garbage collector calls clear() (CF 3.5) - garbage-collection

First thing: This is a compact framework 3.5 application.
I have a very weird problem. In a Dispose-Method the application disposes items in a collection and after that clears the list. So far nothing special and it works like a charm when Dispose is called by my application. But as soon as the Garbage Collector calls the Finalizer, which calls the same Dispose-Method the system throws a NotSupported-Exception on the Clear-Method of the generic collection.
Here is the body of the Dispose-Method:
public override void Dispose()
{
if (items != null)
{
foreach (Shape item in items)
{
item.Dispose();
}
items.Clear();
items = null;
}
base.Dispose();
}
I'm totally stuck here. Maybe someone can explain this to me, or had a similar problem and solved it.

A finalizer needs only call Dispose if there are unmanaged resources to clean up. You cannot attempt to access managed resources when being called from the finalizer.
As mentioned in the comment above, there is no reason [that we can see] that your class should implement a finalizer.
For reference, should you need to use a finalizer, the Dispose pattern to use as follows:
// The finalizer
~MyClass()
{
Dispose(false);
}
// The IDisposable implemenation
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
// The "real" dispose method
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
// Dispose managed objects here
}
else
{
// Free unmanaged resources here
}
_disposed = true;
}
}

Related

C++ CLI Invoke issues

I have a MainForm class (as you'd expect, it is a form) that has a text box on it. I also have another class called 'Application_Server' That does a load of other stuff (not just form-background related, quite a lot of network based stuff etc.).
The Application_Server class runs in it's own thread, but needs to be able to update the controls on the form, for this question, we will stick with just the textbox.
The problem is that even though I am executing the command to set the text of the textBox control via 'Invoke' I am still getting the following exception during runtime:
Additional information: Cross-thread operation not valid: Control
'DebugTextBox' accessed from a thread other than the thread it was
created on.
What could be causing this? I am definitely invoking a delegate within MainForm.
Here are the relevant code segments (cut down for readability):
MainForm.h:
public ref class MainForm : public System::Windows::Forms::Form {
delegate void del_updateDebugText(String^ msg);
del_updateDebugText^ updateDebugText = gcnew del_updateDebugText(this, &MainForm::postDebugMessage);
private: void postDebugMessage(String^ message);
};
MainForm.cpp:
void EagleEye_Server::MainForm::postDebugMessage(String^ message)
{
Monitor::Enter(DebugTextBox);
if (this->DebugTextBox->InvokeRequired)
{
this->Invoke(updateDebugText, gcnew array<Object^> { message });
}
else
{
this->DebugTextBox->AppendText(message);
}
Monitor::Exit(DebugTextBox);
}
And finally, the code calling it:
void ServerAppManager::postDebugMessage(System::String^ message)
{
mainFormHandle->updateDebugText(message);
}
void ServerAppManager::applicationStep()
{
postDebugMessage("Starting\n");
// This is Run in seperate thread in MainForm.cpp
while (s_appState == ApplicationState::RUN)
{
postDebugMessage("Testing\n");
}
}
Thanks!
From background worker called bwSearch we do the call as following from the DoWork event handler:
private: System::Void bwSearch_DoWork(System::Object^ sender, System::ComponentModel::DoWorkEventArgs^ e) {
//... logic
UpdateTxtOutput("Some message");
//... more logic
}
I have a RitchTextBox called txtOutput, also the windows form control containing this code is called frmMain, the UpdateTxtOutput is defined in three parts as follows:
delegate void UpdateTxtOutputDelegate(String^ text);
void UpdateTxtOutput(String^ text)
{
UpdateTxtOutputDelegate^ action = gcnew UpdateTxtOutputDelegate(this, &frmMain::Worker);
this->BeginInvoke(action, text);
}
void Worker(String^ text)
{
txtOutput->AppendText("\t" + text + "\n");
}
I managed to get it working by simplifying the method within the 'MainForm' class to:
void EagleEye_Server::MainForm::postDebugMessage(String^ message)
{
Monitor::Enter(DebugTextBox);
DebugTextBox->AppendText(message);
Monitor::Exit(DebugTextBox);
}
And then moving the 'Invoke' call to the method calling the delegate, not pretty but it works for now. I think the issue may have been caused by the form getting stuck inside an Invoke loop. I say this as I noticed that the form would lock up and stop responding after it hit the recursive Invoke statement.

How can I execute code from the Release / Release All buttons in the Release AR Documents screen

I've got a customization to the Invoice & Memo screen where I execute some custom code (web service calls) when the Release action is activated. This works fine - I knew how to replace the PXAction code and proceeded from there. Now I want to use the Release AR Documents processing screen to do the same thing, but I'm having trouble understanding where / what to override, or where to place my code.
I see the ARDocumentRelease graph constructor with the SetProcessDelegate in the source code, but I'm not sure how to proceed - whether this is where I need to be looking or not. I need to execute my code for each line being released, using the RefNbr in my code.
Since it's an static method, you can't override it. Also, you can't do like it's done in the T300, because you are in processing graph and you can't override the release button with your own. I was able to achieve it by passing callback for each AR document that have been processed.
You can call the Initialize method of the ARDocumentRelease graph to override the logic like you said. After you just have to call ReleaseDoc that uses a callback parameter instead of using the default one.
Here's the code that I came with:
public class ARDocumentRelease_Extension : PXGraphExtension<ARDocumentRelease>
{
public override void Initialize()
{
ARSetup setup = Base.arsetup.Current;
Base.ARDocumentList.SetProcessDelegate(
delegate (List<BalancedARDocument> list)
{
List<ARRegister> newlist = new List<ARRegister>(list.Count);
foreach (BalancedARDocument doc in list)
{
newlist.Add(doc);
}
AddAdditionalLogicToRelease(newlist);
}
);
Base.ARDocumentList.SetProcessCaption("Release");
Base.ARDocumentList.SetProcessAllCaption("Release All");
}
public delegate void PostPorcessing(ARRegister ardoc, bool isAborted);
private void AddAdditionalLogicToRelease(List<ARRegister> newlist)
{
ARDocumentRelease.ReleaseDoc(newlist, true, null, delegate(ARRegister ardoc, bool isAborted) {
//Add your logic to handle each document
//Test to check if it was not aborted
});
}
}
Please note that you must always call static methods from within long running process and create necessary objects there.
Processing delegate logic is implemented as long running process which creates worker thread to execute the processing logic.
You have AddAdditionalLogicToRelease() method which requires object instance in order to call and will fail during thread context switches and hence the issue. So, you must have create object instance inside the thread context and then call instance method.
In general, method that gets called from long running processes are declared static and required objects/graphs are created inside this static method to do some work. See below example how to properly override ARDocumentRelease graph for this purpose:
public class ARDocumentRelease_Extension : PXGraphExtension<ARDocumentRelease>
{
public override void Initialize()
{
Base.ARDocumentList.SetProcessDelegate(
delegate (List<BalancedARDocument> list)
{
List<ARRegister> newlist = new List<ARRegister>(list.Count);
foreach (BalancedARDocument doc in list)
{
newlist.Add(doc);
}
// use override that allows to specify onsuccess routine
ARDocumentRelease.ReleaseDoc(newlist, true, null, (ardoc, isAborted) =>
{
//Custom code here, such as create your GL
});
}
);
}
}
I think it's the function
public static void ReleaseDoc(List<ARRegister> list, bool isMassProcess, List<Batch> externalPostList, ARMassProcessDelegate onsuccess)
under ARDocumentRelease businesss logic.

RxJava Observable Zip Causes Memory Leak

I am using RxJava's Observable.zip method to combine two API calls into one result. For some reason I am getting a memory leak despite the fact that I unsubscribe from the subscription. I am not sure if this a bug on my end or if there is something I need to do with the creation of the Observable.
protected void onCreate(Bundle bundle) {
...
subscription = Observable.zip(
api.getConfiguration(),
api.getSettings().map(r -> r.getData()),
new Func2<ConfigurationResponse, List<Datum>, Struct>() {
#Override
public Struct call(ConfigurationResponse config, List<Datum> data) {
return new Struct(data, config.getCopy(), config.getSettings());
}
}
)
.compose(Schedulers.applyApiSchedulers())
.subscribe(
struct -> {
configurationManager.set(struct.data, struct.copy, struct.settings);
startNextActivity();
},
error -> {
startNextActivity();
}
);
}
protected void onDestroy() {
if (!subscription.isUnsubscribed()) {
subscription.unsubscribe();
}
}
Here is the trace from Leak Canary.
Any help would be appreciated.
I suspect the leak comes from the subscription itself as you seem to keep referencing the Subscriber through it. Try clearing that reference in onDestroy and check again for leaks.
This is probably a leak in retrofit, a similar one seems to have been reported here.
Note that if retrofit leaks the subscriber, you may be able to limit the impact if your mapper func no longer references your activity instance.
In your case Struct is probably a non-static instance class (hence having an implicit reference to the activity instance), if you manage to make it static w/o referencing the activity, you'll likely get rid of this very leak.

Ninject Transient Scope + Scope Disposal + Garbage Collection + Memory Leak

I am new at this (I'm still learning), I would appreciate very much if you Jedi masters out there can help me out with the question and concern that I have.
I want to use Ninject and I have the codes below, I would like to know whether my objects will get disposed properly and garbage collected.
For Ninject's default Transient Scope, I read that "Lifetime is not managed by the Kernel (the Scope object is null) and will never be Disposed."
If I would to use my codes in production, especially when I get lots of concurrent calls to my WebApi (POST), will it cause any problems like Memory Leak, etc?
What would be the best Ninject's Object scope to use for this situation?
By the way, if I don't specify the object scope like "kernel.Bind().To();", will it default to TransientScope?
public class VehicleClassRepository : IVehicleClassRepository
{
SomeDataContext context = new SomeDataContext();
public IQueryable<VehicleClass> All
{
get { return context.VehicleClasses; }
}
public IQueryable<VehicleClass> AllIncluding(params Expression<Func<VehicleClass, object>>[] includeProperties)
{
IQueryable<VehicleClass> query = context.VehicleClasses;
foreach (var includeProperty in includeProperties) {
query = query.Include(includeProperty);
}
return query;
}
public VehicleClass Find(int id)
{
return context.VehicleClasses.Find(id);
}
public void InsertOrUpdate(VehicleClass vehicleclass)
{
if (vehicleclass.VehicleClassId == default(int)) {
// New entity
context.VehicleClasses.Add(vehicleclass);
} else {
// Existing entity
context.Entry(vehicleclass).State = EntityState.Modified;
}
}
public void Delete(int id)
{
var vehicleclass = context.VehicleClasses.Find(id);
context.VehicleClasses.Remove(vehicleclass);
}
public void Save()
{
context.SaveChanges();
}
public void Dispose()
{
context.Dispose();
}
}
public interface IVehicleClassRepository : IDisposable
{
IQueryable<VehicleClass> All { get; }
IQueryable<VehicleClass> AllIncluding(params Expression<Func<VehicleClass, object>>[] includeProperties);
VehicleClass Find(int id);
void InsertOrUpdate(VehicleClass vehicleclass);
void Delete(int id);
void Save();
}
In my NinjectWebCommon.cs:
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IVehicleClassRepository>().To<VehicleClassRepository>();
}
In my WebApi's VehicleClassController.cs:
public HttpResponseMessage Post(VehicleClass value)
{
if (value == null)
{
return new HttpResponseMessage(HttpStatusCode.BadRequest);
}
else
{
vehicleclassRepository.InsertOrUpdate(value);
vehicleclassRepository.Save();
return new HttpResponseMessage(HttpStatusCode.Created);
}
}
Late answer (almost 2 years) but in case others read this...
Although it's true that the garbage collector will eventually dispose of your VehicleClassRepository instance, you'll very likely run into problems before then.
Your data context likely holds an open db connection until it's disposed. The db connection probably comes from a pool of db connections.
So long before the CLR ends up garbage collecting these (which would also dispose them), incoming requests end up blocking while trying to get a db connection but there are none available.
I've encountered this type of behavior and learned from it the hard way. So the VehicleClassRepository should be scoped in dependency scope so that you get one per call and more importantly, it'll get disposed immediately after the call is done.

Ninject 2.0 InRequestScope() causing me problems - dependencies not being disposed

I'm using Ninject 2.0 with an MVC 2/EF 4 project in order to inject my repositories into my controllers. I've read that when doing something like that, one should bind using InRequestScope(). When I do that, I get a new repository per request, but the old repositories aren't being disposed. Since the old repositories are remaining in memory, I get conflicts with multiple ObjectContexts existing at the same time.
My concrete repositories implement IDisposable:
public class HGGameRepository : IGameRepository, IDisposable
{
// ...
public void Dispose()
{
if (this._siteDB != null)
{
this._siteDB.Dispose();
}
}
}
And my Ninject code:
public class NinjectControllerFactory : DefaultControllerFactory
{
private IKernel kernel = new StandardKernel(new HandiGamerServices());
protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
{
try
{
if (controllerType == null)
{
return base.GetControllerInstance(requestContext, controllerType);
// return null;
}
}
catch (HttpException ex)
{
if (ex.GetHttpCode() == 404)
{
IController errorController = kernel.Get<ErrorController>();
((ErrorController)errorController).InvokeHttp404(requestContext.HttpContext);
return errorController;
}
else
{
throw ex;
}
}
return (IController)kernel.Get(controllerType);
}
private class HandiGamerServices : NinjectModule
{
public override void Load()
{
Bind<HGEntities>().ToSelf().InRequestScope();
Bind<IArticleRepository>().To<HGArticleRepository>().InRequestScope();
Bind<IGameRepository>().To<HGGameRepository>().InRequestScope();
Bind<INewsRepository>().To<HGNewsRepository>().InRequestScope();
Bind<ErrorController>().ToSelf().InRequestScope();
}
}
}
What am I doing wrong?
I'm quite sure that you are wrong about the guess that your objects are not disposed. This just does not happen when you think it will happen. But the fact that this does happen later should not give you any problems with ObjectContexts unless you are doing something wrong. With a high load you will have a lot of ObjectContexts at the same time anyway.
What can become a problem though is that the memory usage increases. That's why the request scope needs to be released actively. The Ninject MVC extensions will take care of that. Otherwise have a look at the OnePerRequestModule to see how it is done:
https://github.com/ninject/Ninject.Web.Common/blob/master/src/Ninject.Web.Common/OnePerRequestHttpModule.cs

Resources