This console app ends before reaching the end, i know that because it usually scans a whole Table in a DB with 5000-10000 rows.
I have no idea as to why it quits halfway, because it has no exeptions or any information (it just shows no information in the logs it just "stops"), and after aproximatly 10-15 mins it abruply stops and exits like everything is fine and it just reached the end of it. When i check the db only 1000-2000 registers have been worked on.
The Code : (Rather simple function any clarification ask and i shall give it, not a reproductive example because its a big development but i will point out what type of information everything is with as much detail as possible)
private List<Item> artigos;
public void VerifyID()
{
//a list cointaining all the rows in the db
artigos = itemCore.GetAllSEAAll();
foreach (var artigo in artigos.ToList())
{
try
{
//Code Here
}
catch(Exception ex)
{
logger.LogInformation(ex.ToString());
}
}
}
TL:DR on code :
I get 5000-10000 rows from a table.
I check a specific field on it and compare to a value (irrelevant for the question) that comes from an api.
I update the db in order to register any anomalies.
(Updated to include only needed code)
It will reproduce the problem i have its just least predictable as to how long until it stops, I am pretty sure it HAS something to do with Garbace Collector or Memory Management
I have so far tried to stop the garbage collector from collecting my variable (artigos).
Resulting is a few (3-5) results of (Object not Initialized) before it quits.
From debbuging i managed to figure out that List artigos, at some point stops existing, GC.KeepAlive() does nothing.
I have searched the web for a similar issue without any luck.
That being and my lack of experience i am currently stuck on what to do, or even what "path" to take to figure out, any help is welcome and sorry if i am missing anything im not familiar with StackOverflow structure
I need to make this clear, i have debuged this program more then i care to remember.
It is not my code that sets artigos to null.
There is no exeption being thown.
Related
This is my first question here so please go easy on me. :)
I'm also new to Blazor but not c#.
I am building a Blazor server-side application where a user can enter some information and check if it's valid or not based on some data on the server.
So far I have no issues with calling the function of the class that does the lookup and returns a record to display on the browser.
My problem comes when I want to display that information.
In the c# code, I have a variable called SdItem which contains the record that comes back from the query.
To display the data on the razor page I use the following lines.
#if (SdItem != null)
{
<div>
Code: #SdItem.Code<br />
Desc.: #SdItem.Desc<br />
</div>
}
When SdItem gets the data it obviously does not display the information until I call StateHasChanged();
This of course throws an exception so I had to change it to await InvokeAsync(StateHasChanged);
Although after this change the information shows on the screen and all seems to be fine, I came across a new issue which I could not find a solution or an explanation anywhere on the internet.
During debugging, MS Edge automatically starts and displays the website.
To test this strange issue I also start Firefox to point to the same local address.
Then I use my smartphone as well and that is where I start the query.
When I get the results back, not only do they show up on the phone but on all active browsers that are currently displaying the site.
Why does this happen and how can I stop it.
At the moment I managed to stop this from happening with an ugly code
try { StateHasChanged(); } catch { }
This suppresses the exception and the result is only being displayed on the browser that does the request. This is ugly and I don't like to use it.
Any help would be appreciated.
Just as information, in case this could be the reason. The queried data is in a List in a class which is added as a scoped service. But T is a private variable in the code on the razor file.
"When SdItem gets the data it obviously does not display the information until I call StateHasChanged" Why is this obvious? I would expect Blazor to update the display whenever displayed data is changed. You should very rarely need to call StateHasChanged. This makes me wonder what else is going on.
First thought that springs to mind is that SdItem should be a property...
public Whatever SdItem { get; set; }
...and not a private field...
private Whatever SdItem;
I'm not sure if needs to be public, but when using properties, Blazor (almost) always updates the display. When using private fields, if often doesn't.
"This of course throws an exception" Again, I don't see why this is so obvious that you say "of course." It all depends on where you are calling StateHasChanged. Yes, if you're inside an async block then you'll need to call InvokeAsync, but if you arent, then you shouldn't need to do that.
More code would be useful, as its hard to know exactly what you're doing from the small snippet you provided, but try using a property (if you aren't already), and see if that avoids the need to call StateHasChanged.
If not, please update your question with more information.
I am struggling with memory issue which I can definitely see but I don't know where and when exactly it's happening.
My managed heap size seems to be ok (100MB), but native heap size is starting to growing in unknown moment and it's still going until it will reach ~2GB and app is crashing.
My application is running many threads, and it's doing a lot of Db connection through EF 6 in many loops.
That's why it's really hard for me to debug code just by looking to logs or putting break points.
I thought maybe I can see what's the issue by looking at memory but what only I can see it's that my native heap size is mostly filled by objects with size of 8,192 bytes. So I can see that problem is really happening but still have no clue why.
I am not sure if I am using 100% capabilities of Visual Studio memory profiler.
What I can see now is:
What else or more I can do to find the issue?
Maybe it's silly question but I am working on this problem for two days and I've almost reached my ideas limit.
I've went through Break points, logs, code analyze but I am still without any clue.
I will be grateful for any idea.
[EDIT] 15:11 2017/02/03
I was able to find code responsible for the leak, but it still has no sense for me. How it's possible that this code is causing massive memory leak?
The code is :
public class DbData : IDisposable
{
private DBEntity db;
public DbData()
{
db = new FruitDBEntity();
}
public Fruit AddFruitDefinition(Fruit fruit)
{
lock (thisLock)
{
var newFruit = db.Fruits.Where(f => f.FruitId == fruit.FruitId)
.Where(f => f.FruitName == fruit.FruitName)
.Where(f => f.FruitColor == fruit.FruitColor)
.FirstOrDefault();
if (newFruit == null)
{
newFruit = db.Fruits.Add(fruit);
db.SaveChanges();
}
return newFruit;
}
}
}
Class DbData is created every time I want to use method AddFruitDefinition():
using ( var data = new DbData() )
{
data.AddFruitDefinition();
}
First, you need at least two snapshots.
As far as I can see (from image) you took only one snapshot.
What to do?
Start application with profiler.
Do usual steps and take snapshot.
Repeat same steps which you did in step 2, and take another snapshot.
Stop application. You should see 2 snapshots, click on 2ns snapshot and select Compare to #Snapshot 1.
It might take some time to process results.
You should be able to see few additional columns in report (Identifier, count, Size, Module, Count Diff. Size Diff.
Last two columns are important. They tell which class used more/less memory second time.
To sum up... you need to figure out where is memory leak and to fix it. And you'll do it by comparing snapshots.
Look at the following code:
public static string GetCleanURL(string baseURL, string url)
{
string cleanUrl = url.ToLower();
if (cleanUrl.StartsWith("http://"))
{//It already starts with http:// It is already in the correct form return it.
return cleanUrl;
}
The 'url' value passed in is "123.123.123.123:1234/myurl/withstuff.xml". In the 'if' statement, the value for 'cleanUrl' is "123.123.123.123:1234/myurl/withstuff.xml". But for some reason, the code execution goes inside of the if block and 'return cleanUrl;' gets executed.
Here is a screenshot of the current value for 'cleanUrl':
When I plug cleanUrl.StartsWith("http://") into the 'Immediate Window' of my debugger, it returns false. Which is what I would expect. However, the execution is somehow going into the if block as though it had returned true.
Can anybody please explain how this is possible?
SOLVED !!!
I appreciate those of you who helped me out on this one.
I needed to Clean and Rebuild my project and Close and Reopen Visual Studio 2013 about 4 times before the code base and debug stuff was actually in sync. It now appears to be working correctly.
Not sure why it ever got that way, or why I needed to do Clean/Rebuild several times before things synced up. But it is working now.
So, friends, if ever you find your code is just acting crazy and not doing what it should do. Just realize that anybody in their right mind would never become a programmer. Then do a clean / rebuild a few times and pray that the oddity goes away never to return.
Thanks for all your help on this one.
I LOVE fighting with the development tools...
No, StartWith isn't buggy, and works as expected.
Try the minimal code below. Reduce your code to the minimum amount to reprouce the problem. Does this happen everytime?
Does it happen with more than one candidate string? Or only that string?
Something else is going on sorry, the following writes Doesn't start
static void Main(string[] args)
{
string cleanUrl = "123.123.123.123:1234/SomeFile.xml";
if (cleanUrl.StartsWith("http://"))
Console.WriteLine("Starts");
else
Console.WriteLine("Doesn't start");
Console.ReadLine();
}
I am writing an application that will do some processing on the live preview images on windows phone 8. To achieve a good performance, I decided to use to the native interfaces provided with new sdk. Everythings work Ok for initializing the camera in native side, and feeding frames to a Image component in xaml. Now, I will write the code that will run in OnFrameAvailable method.
My problem is getting a processed value from the native component. Just to make things as simple as possible I just set an integer value in OnFrameAvailable and wrote an accessor of this value through a WinRT component to make it accesible in managed side.
I got stuck on what is an elegant way of accessing this value. When I try to access it in a loop in a thread i get the notorious "attempted to read or write protected memory " exception. I know the code does not make very much sense but I tried to minimize to point out the issue.
Here is how I do it:
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
nativeCapture = new NativeCapture();
while (nativeCapture.Done == false) ;
viewFinderBrush.SetSource(nativeCapture.NPhotoCaptureDevice);
DrawElementThread = new Thread(drawElementsFunction);
DrawElementThread.Start();
base.OnNavigatedTo(e);
}
void drawElementsFunction()
{
while(true)
{
int a = nativeCapture.DetectedRectangleCoordinates; // Exception occurs here
}
}
Here you'll also notice that I am accsessing another value, Done, but I dont get the exception for it. However, I should note that is just set in the constructor of the native component whereas DetectedRectangleCoordinates is set everytime OnFrameAvailable called which I expect anytime a preview frame from the camera is available.
Therefore, I susptected that there might be some locking mechanism on WinRT components. Each time the OnFrameAvaible method called DetectedRectangleCoordinates becomes unaccessible. However, I could not find a statement about this and couldn't figure out how to debug such a thing.
I would really appreciate if you provide me with some pointers related to this or similar issues? Is it something related to access mechanisms in WinRT components? Or it is a bad threading practice I am doing? If so, how would I synchronize the thread in managed code and native code?
EDIT:
Putting a breakpoint on the line giving the exception and stepping does not cause the exception, and I get the expected value.
EDIT:
I put a breakpoint on the get function on native side. this pointer is pointing to null there. I could not understand why it is because it is being called from the object that is just constructed. ( nativeCapture object).
I have worked quite some time on what may be going wrong, but adding the code to Loaded event handler of the page solved the issue. I am not sure what it is related about, but when the code piece I have given in the question is run in OnNavigatedTo method, nativeCapture component might have self null pointer (this->) on its methods.
I hope this could help people if they have similar problems.
I got an OutOfMemoryException earlier and couldn't figure out what it was for. It made no sense at all. Dug around in my code, and suddenly remembered that somewhere had forgotten to check for null, and in this particular case it was (and should be) exactly that. That shouldn't cause an OutOfMemoryException in my opinion, but I fixed it anywas of course. And when I did, the exception didn't appear anymore!
So I removed the check again and studied the exception I got some more. And turns out it had an InnerException of type NullReferenceException and a stack trace which of course made a lot more sense.
But why did I get an OutOfMemoryException? This has never happend to me before... makes no sense to me...
Would love to give some more context, but can't really say much without having to upload the whole project, which I can't (And which you wouldn't want to read through anyways :p). But the specific place it happend looks like this:
{
foreach (var exportParameter in exportParameters)
{
// Copy to local
var ep = exportParameter;
// Load stored values from db
...
}
int i = 1;
exportParameters
.OrderBy(ø => ø.Sequence)
.ForEach(ø => { if (!ø.Locked) ø.Sequence = i++; });
}
The fix was to put an if(exportParameters != null) before the code block. exportParameters is a List<ExportParameter>, except in the failing case in which it was null.
You might be facing the problem that Constrained Execution Regions are designed to prevent - that is, the JITting of some code that your catch clause relies on is causing the out of memory condition.
(In response to svish's comment, this is the first link when googling the phrase: http://msdn.microsoft.com/en-us/library/ms228973.aspx)
Aside from the obvious reason for getting an OOMException, you can also get it if you still have memory available, just not a big enough chunk for what is being requested. If you're getting it reliably and relatively near startup, you're probably accidentally requesting more memory than you intend to (ie. requesting a very large array). Can you post a bit of your code or at least describe your allocation pattern?