Does the below code leaks memory? If so, any recommendations on optimising it?
SPWeb web = (SPWeb)properties.Feature.Parent; // comes from the event receiver
//... lots of other code
// the below is the focal point.
foreach (SPWeb childWeb in web.Webs)
{
try
{
// lots of heavy processing with the childWebs
}
finally
{
if (childWeb != null)
{
childWeb.Dispose();
}
}
}
The code you have posted should be fine. However, depending on what you do with the childWeb within the try-statement, it might cause memory leaks. Can you post the entire code? Do you suspect memory leaks?
According to Disposing Objects, your code matches the Good Coding Practice for SPWeb.Webs.
As mentioned on that page, I would recommend downloading and using SPDisposeCheck as both verification of correct code and identification of potential memory leaks.
Related
I am trying to access pixel data and save images from an in-game camera to disk. Initially, the simple approach was to use a render target and subsequently RenderTarget->ReadPixels(), but as the native implementation of ReadPixels() contains a call to FlushRenderingCommands(), it would block the game thread until the image is saved. Being a computationally intensive operation, this was lowering my FPS way too much.
To solve this problem, I am trying to create a dedicated thread that can access the camera as a CaptureComponent, and then follow a similar approach. But as the FlushRenderingCommands() block can only be called from a game thread, I had to rewrite ReadPixels() without that call, (in a non-blocking way of sorts, inspired by the tutorial at https://wiki.unrealengine.com/Render_Target_Lookup): but even then I am facing a problem with my in-game FPS being jerky whenever an image is saved (I confirmed this is not because of the actual saving to disk operation, but because of the pixel data access). My rewritten ReadPixels() function looks as below, I was hoping to get some suggestions as to what could be going wrong here. I am not sure if ENQUEUE_UNIQUE_RENDER_COMMAND_ONEPARAMETER can be called from a non-game thread, and if that's part of my problem.
APIPCamera* cam = GameThread->CameraDirector->getCamera(0);
USceneCaptureComponent2D* capture = cam->getCaptureComponent(EPIPCameraType::PIP_CAMERA_TYPE_SCENE, true);
if (capture != nullptr) {
if (capture->TextureTarget != nullptr) {
FTextureRenderTargetResource* RenderResource = capture->TextureTarget->GetRenderTargetResource();
if (RenderResource != nullptr) {
width = capture->TextureTarget->GetSurfaceWidth();
height = capture->TextureTarget->GetSurfaceHeight();
// Read the render target surface data back.
struct FReadSurfaceContext
{
FRenderTarget* SrcRenderTarget;
TArray<FColor>* OutData;
FIntRect Rect;
FReadSurfaceDataFlags Flags;
};
bmp.Reset();
FReadSurfaceContext ReadSurfaceContext =
{
RenderResource,
&bmp,
FIntRect(0, 0, RenderResource->GetSizeXY().X, RenderResource->GetSizeXY().Y),
FReadSurfaceDataFlags(RCM_UNorm, CubeFace_MAX)
};
ENQUEUE_UNIQUE_RENDER_COMMAND_ONEPARAMETER(
ReadSurfaceCommand,
FReadSurfaceContext, Context, ReadSurfaceContext,
{
RHICmdList.ReadSurfaceData(
Context.SrcRenderTarget->GetRenderTargetTexture(),
Context.Rect,
*Context.OutData,
Context.Flags
);
});
}
}
}
EDIT: One more thing I have noticed is that the stuttering goes away if I disable HDR in my render target settings (but this results in low quality images): so it seems plausible that the size of the image, perhaps, is still blocking one of the core threads because of the way I am implementing it.
It should be possible to call ENQUEUE_UNIQUE_RENDER_COMMAND_ONEPARAMETER from any thread since there is underlying call of Task Graph. You can see it, when you analize what code this macro generates:
if(ShouldExecuteOnRenderThread())
{
CheckNotBlockedOnRenderThread();
TGraphTask<EURCMacro_##TypeName>::CreateTask().ConstructAndDispatchWhenReady(ParamValue1);
}
You should be cautious about accessing UObjects (like USceneCaptureComponent2D) from different threads cause these are managed by Garbage Collector and own by game thread.
(...) but even then I am facing a problem with my in-game FPS being jerky whenever an image is saved
Did you check what thread is causing FPS drop with stat unit or stat unitgraph command? You could also use profiling tools to perform more detailed insight and make sure there is no other causes of lag.
Edit:
I've found yet another method of accessing pixel data. Try this without actually copying data in for loop and check, if there is any improvement in FPS. This could be a bit faster cause there is no pixel manipulation/conversion in-between.
This code:
while (true) {
new ThreadFactory() {
#Override
public Thread newThread(Runnable r) {
return null;
}
};
}
make the JVM go out of memory very quickly.
Why?
I have tried to run this code with JRE 1.7.0_60 x86_64 on Windows 7 with default options and here are the results:
Author's code being run as is doesn't seem to perform any allocation at all, most likely because JIT detects unused references;
Modified version of code that outputs created threadFactorys to System.out results in "saw-like" heap usage pattern:
Which means that both allocation and garbage collection takes place.
Back to your question: I think you missed some significant parts of the code, or put -Xmx to extremely low value, or some other reason. The code you posted is ok, though.
I am trying to write a multithreaded WinForm in C++/CLI app using VS2012.
I know that only the UI thread can update a control and I have been using delegates and the invoke methods. However, I have run into a memory access issue when using BeginInvoke that I do not see when using Invoke.
Delegate Function:
public: delegate void pictureboxShowDelegate(int tChannelNumber,System::Windows::Forms::PictureBox^,System::Drawing::Bitmap^ colorImage);
Called Function:
void DrawCVImageShow(int tChannelNumber, System::Windows::Forms::PictureBox^ PBox, System::Drawing::Bitmap^ b)
{
if(PBox->InvokeRequired)
{
pictureboxShowDelegate^ d = gcnew pictureboxShowDelegate(this,&MyForm::DrawCVImageShow);
PBox->Invoke(d,tChannelNumber,PBox,b);
}
else
{
System::Drawing::Graphics^ graphics = PBox->CreateGraphics();
System::Drawing::RectangleF rect(0,0,(float)PBox->Width,(float)PBox->Height);
graphics->DrawImage(b,rect);
}
}
If called this way, it works with no problem.
If I substitute BeginInvoke for Invoke, I get an AccessViolationException.
Clearly, this has to do with the garbage collection of the parameters but I simply can't figure this one out.
Any help greatly appreciated.
Thanks
It sounds to me like whatever is calling DrawCVImageShow in the first place is Disposing the bitmap immediately after DrawCVImageShow returns.
If that's the case, there are a couple possiblities:
Make it so that DrawCVImageShow is the one responsible for Disposing the bitmap, not whatever calls DrawCVImageShow. (Simple solution, though probably not the best from an engineering solution: The thing that created the bitmap should generally be responsible for disposing it, and it makes DrawCVImageShow a less general method.)
Make a Clone of the bitmap, and dispose that one after it's been used. This is the more proper solution, in my opinion, but it does make things a little bit more complicated. You now need two versions of DrawCVImageShow, one that disposes the bitmap (for BeginInvoking), and one that doesn't (the method you have now). This also means you'll have two copies of the bitmap in memory when a BeginInvoke is needed; hopefully these bitmaps are not so large that this is an issue.
Dear Community. I like to understand a little task, which have to help me improve performance for my application.
I have array of dictionaries, in singleton area with objects NSDictionary and keys
code
country
specific
I have to receive country and specific values from this array.
My first version of application was using predicate, but later i find a lot of memory leaks and performance issues by this way. Application was too slow and don't empty very quickly a memory stack, coming to around 1G and crash.
My second version was little bit more complicated. I was filled array in singleton area with objects per one code and function, which u can see bellow.
-(void)codeIsSame:(NSArray *)codeForCheck;
{
//#synchronized(self) {
NSString *code = [codeForCheck objectAtIndex:0];
if ([_code isEqualToString:code])
{
code = nil;
NSUInteger queneNumberInt = [[codeForCheck objectAtIndex:1] intValue];
NSLog(#"We match code:%# country:%# specific:%# quene:%lu",_code, _country,_specific, queneNumberInt);
[[ProjectArrays sharedProjectArrays].arrayDictionaryesForCountryCodesResult insertObject:_result atIndex:queneNumberInt];
}
code = nil;
//}
return;
}
The way to receive necessary issues is a :
SEL selector = #selector(codeIsSame:);
[[ProjectArrays sharedProjectArrays].myCountrySpecificCodeListWithClass makeObjectsPerformSelector:selector withObject:codePlusQueueNumber];
This version working much better, no memory leaks, very quickly, but too hard to debug. Sometimes i receive empty result, i tried to synchronize thread jobs, but it still not work stable. The main problem in this way is that in strange reason sometimes i don't have result in my singleton array. I tried to debug it, using index of array for different threads, and have result that class just missed answer.
Core data don't allow me to make copy of main MOC and for multithreading design i can't using it (lock and unlock is not good idea, and that's way product too much error in lock/unlock part of code.
Maybe anybody can suggest, what i can do better in this case? I need a best way to make decision which will work stable, will be easy to coding and understand it?
My current solution is using NSDictionary, where is a keys is a code and under that code i have dictionary with country/specific. Working fine as well, but don't decide a main task - using core data if u need multiply access from too many threads to the same data.
I’m writing a test that expects to receive an event from an object that it is calling. Specifically, I am calling out to an object that connects to an AIX machine via SSH (using the open source Granados project), then disconnecting, and I want to make sure I receive the OnConnectionClosed event that is being raised during the disconnect. It sounds simple enough, and I’ve written many tests like this in the past, but this time some strange behavior is occurring that I believe is related to threading.
Basically, the object I call is raising the ‘OnConnectionClosed’ event on a different thread than what I call it from. What I’m seeing is that when I run the test by selecting ‘Debug Test’ from the UI, it passes, but if I choose ‘Run Test’, it fails (even if there are no breakpoints set during the debug run). I’ve done some Googling and found this post that seems to indicate that by default the MSTest host runs in Single Thread mode but that a config change can make it run in Multi Thread mode. This sounded like it would logically fix my problem, but of course, it did not.
Some other posts I’ve come across also make me think that MSTest is simply not monitoring the background threads (so the events raised by them are not being ‘heard’). This would also make sense, and since it seems to work in debug mode, and it seems like the fix above should logically solve that problem, then I’m confused as to why it’s not working. It is possible that I’m simply not correctly dealing with the threads, although I would expect that to still be a problem in debug mode if it were the case.
Has anyone else tried to test something in a similar way? If so, did you encounter similar problems? And if so, how did you resolve them?
I’ve pasted the relevant unit test code below (I’ve removed the connection info for security reasons).
[TestClass]
public class SSHReaderTests
{
private bool received = false;
private delegate bool SimpleFunc();
[TestInitialize]
public void MyTestInitialize()
{
received = false;
}
[TestMethod]
public void Should_raise_OnReaderConnectionClosed_event_after_successful_connection_is_disconnected()
{
IReader reader = new SSHReader();
reader.OnReaderConnectionClosed += delegate
{
received = true;
};
reader.Connect("*****", "*****", "*****");
//Assert.IsTrue(reader.IsConnected);
reader.Disconnect();
//Assert.IsFalse(reader.IsConnected);
Assert.IsTrue(WaitUntilTrue(delegate {
return received; }, 30000, 1000));
}
private static bool WaitUntilTrue(SimpleFunc func, int timeoutInMillis, int timeBetweenChecksInMillis)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
while(stopwatch.ElapsedMilliseconds < timeoutInMillis)
{
if (func())
return true;
Thread.Sleep(timeBetweenChecksInMillis);
}
return false;
}
}
Use the WaitHandle classes in the System.Threading namespace. Either, AutoResetEvent or ManualResetEvent. The difference between the two is that AutoResetEvent lets one thread proceed each time it is set, while ManualResetEvent releases all waiting threads on set.
The reason your example doesn't work has to do with compiler optimizations. The code does not actually get compiled to what you would think at first glance. Most likely, the compiler will do something like place the local variable in a register and never actually fetch it during your loop that checks. You can avoid this type of thing with the volatile keyword, but I would highly recommend reading up on threading and concurrency for more details. Joe Duffy's blog at http://www.bluebytesoftware.com is a great resource to get started, and I highly recommend his Concurrency Programming on Windows book that is coming out soon.
Not exactly what you arr asking about, but you may find some workable solutions or at least ideas by checking out the MS Research project called CHESS. It's for multithreaded concurrency testing in .net.