|
|
hey peeps
can someone please BRIEFLY explain the word "memory leak" to me?
ive come across something strange in a test app im writing, im communicating to a external device via LAN using an SDK provided by the manufacturer. The documentation keeps commenting parts of code "Critical! Without disposing, you'd have a memory leak."
what happens in my app is sometimes i close it but visual studio stays in debug mode? is this a memory leak?
thanx
Harvey Saayman - South Africa
Junior Developer
.Net, C#, SQL
think BIG and kick ASS
you.suck = (you.passion != Programming)
|
|
|
|
|
|
A memory leak means your program or library is allocating memory and never freeing it. Since the CLR managed memory for you, this shouldn't be an issue. But there are some things to watch out for:
if you you objects that implement IDisposable, you should call Dispose on them when you're done. Read up on IDisposable[^].
Another thing to watch out for is listening for events on live objects. Say you have an object that will be around for the program's duration, longLivingObject. It has an event called Changed on it. Now imagine you create 1,000,000 short lived objects during the duration of the program. Each one listens for the Changed event on longLivingObject. Now you'll have a leak: all the shortLivedObjects will stay in memory because the longLivedObject is holding a reference to each shortLivedObject through the event. longLivedObject is keeping the 1,000,000 short lived objects in memory.
|
|
|
|
|
Hi,
i have troubles with a C# wrapper for one of my libraries. The C declaration looks like this:
int find(void *h, void *reserved, key *key, record *record, int flags);
The function searches a database for "key" and, if successfully, fills "record" with the values. In C# record structure looks like this (the only important members are "size" and "data").
[StructLayout(LayoutKind.Sequential)]
unsafe struct RecordStruct
{
public Int32 size;
public void *data;
public Int32 flags;
public Int32 _flags;
public Int64 _rid;
}
And here is my C# function wrapper:
[DllImport("database.dll", EntryPoint = "find",
CallingConvention = CallingConvention.Cdecl)]
static private extern int FindLow(IntPtr handle, IntPtr reserved,
ref KeyStruct key, ref RecordStruct record, int flags);
static public unsafe byte[] Find(IntPtr handle, byte[] data, int flags) {
KeyStruct key = new KeyStruct();
RecordStruct record = new RecordStruct();
key.size = (short)data.GetLength(0);
fixed (byte* bk = data) {
key.data = bk;
int st = FindLow(handle, IntPtr.Zero, ref key, ref record, flags);
if (st == 0) {
return record.data;
}
throw new DatabaseException(st);
}
}
My problem is that RecordStruct.data is a void* byte array, and RecordStruct.size is the size of the array. But how can i create a C# byte[] from this pointer?
If possible, i would like to avoid copying the array contents, which would mean a huge performance penalty (but that would also mean that the void* pointer must not be moved around by the garbage collector...)
Thanks
Christoph
|
|
|
|
|
I am not sure about the following code block; but you can give a try
<br />
fixed (byte* bk = data)<br />
{<br />
key.data = bk;<br />
int st = FindLow(handle, IntPtr.Zero, ref key, ref record, flags);<br />
if (st == 0)<br />
{<br />
IntPtr recData = new IntPtr(record.data);<br />
byte[] newArray = new byte[record.size];<br />
Marshal.Copy(recData, newArray, 0, record.size);<br />
return newArray;<br />
}<br />
throw new DatabaseException(st);<br />
}<br />
Please check whether record.data has to be pinned or not.
*jaans
|
|
|
|
|
yes, it works Thanks for your help. I'm not happy about the copying, but i guess it can't be avoided.
How can i pin it? with fixed()?
|
|
|
|
|
hi ,
i only wanna run single exe for my application if second is tried to run
show a message only one exe can run in one time.
For C# there is a easy way for this?
|
|
|
|
|
Please use the search[^], there's loads of examples.
Standards are great! Everybody should have one!
|
|
|
|
|
Two ways that I know of.
1. Use a Mutex, a bit of googling should find you loads of examples - some better than others. Avoid ones that use the process name as if someone copies your exe and renames it they'll be able to run both instances.
2. Using the VisualBasic namespace, a bit of fiddling with Program.cs file and it works as VB has an easy way of setting it - but using VB always feels wrong (IMO) in C#
Dave
|
|
|
|
|
I create multiple pictureboxes on one big parent picturebox with following code:
void btn_transfo_MouseDown(object sender, MouseEventArgs e)<br />
{<br />
teller_transfo += 1;<br />
PictureBox transfo = new PictureBox();<br />
transfo.Name = "transfo" + teller_transfo;<br />
transfo.ClientSize = new Size(50, 50);<br />
transfo.SizeMode = PictureBoxSizeMode.StretchImage;<br />
try<br />
{<br />
transfo.Image = Image.FromFile(@"c:\pic\transfo.jpg");<br />
}<br />
catch (Exception error)<br />
{<br />
MessageBox.Show(error.Message, "Cannot find pic", MessageBoxButtons.OK, MessageBoxIcon.Error);<br />
}<br />
transfo.MouseDown += new MouseEventHandler(transfo_MouseDown);<br />
transfo.MouseUp += new MouseEventHandler(transfo_MouseUp);<br />
transfo.MouseMove += new MouseEventHandler(transfo_MouseMove);<br />
transfo.MouseDoubleClick += new MouseEventHandler(transfo_MouseDoubleClick);<br />
transfo.MouseClick += new MouseEventHandler(transfo_MouseRightClick);<br />
picCanvas.Controls.Add(transfo);<br />
this.DoDragDrop(transfo, DragDropEffects.Move);<br />
}
I have created a context menu on right click with this code:
void transfo_MouseRightClick(object sender, MouseEventArgs e)<br />
{<br />
if (e.Button == MouseButtons.Right)<br />
{<br />
PictureBox x = sender as PictureBox;<br />
cxt_Transfo.Show(x, new Point(e.X, e.Y));<br />
}<br />
}
This all works fine, no i have added a button in the context menu to remove the picturebox i right clicked on:
void cxt_btn_transfoVerwijder_MouseDown(object sender, MouseEventArgs e)<br />
{<br />
PictureBox x = sender as PictureBox; <br />
picCanvas.Controls.Remove(x);<br />
}
The picturebox does't get removed.. what do i wrong?
Thx
|
|
|
|
|
Hello,
Have you debugged it?
The problem is, that you handle the MouseDown of the Button, and then try to cast the sender (which is the Button) to a PictureBox.
I would say, that "PictureBox x" (in your "cxt_btn_transfoVerwijder_MouseDown") is "null".
Apart from that, you should also Dispose the Instance of the PictureBox and remove all other references.
P.S.: Naming an PictureBox "x" doesn't make it easy for us to help you!
All the best,
Martin
|
|
|
|
|
Hi,
Can someone tell me how to extract images and store it separately from an excel file using C# code?
Regards
Diptanil
|
|
|
|
|
If you try to extract a excel generated diagramm, the only chance is via screenshot. you cannot render the grafic without opening excel.
|
|
|
|
|
Hi,
I have some images which are not generated by Excel itself. I need to invoke a program which will read the excel file and store the imgaes inside separately. Can you help me with a valid C# code for doing that.
Regards
|
|
|
|
|
Hi,
I am a small business owner looking for an individual to finish and maintain an Outlook plug-in written in C#. The application is functional at this point but needs an installer and exposure to clients and subsequent bug fixes along with occasional revisions.
If you are interested in a small long term project please feel free to make contact.
|
|
|
|
|
Dear all,
I have two treeviews on my form , and the afterselect method on both of them is like this :
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)<br />
{<br />
tabControl1.Visible = false;<br />
}<br />
<br />
private void treeView2_AfterSelect(object sender, TreeViewEventArgs e)<br />
{<br />
tabControl1.Visible = true;<br />
}
The problem that I have, is that the tabcontrol that I would like to hide or show, only hides or shows once. After that, nothing happens anymore if I click on either treeviews. I tried attaching a messagebox to the methodes for debug reasons, but they don't show either. It looks like the afterselect method is not being called the second or third time I click on it.
Can anyone help me out please ?
kind regards,
Rick
|
|
|
|
|
The AfterSelect event fires after you select a specific node on the treeview, not the treeview itself. Once this has been selected, it will not fire again untill you select another node on the same tree. Sounds like what you want is to simply perform an action when a treeview is clicked, so you might as well use the Click event. Hope this helps.
Standards are great! Everybody should have one!
|
|
|
|
|
Hi,
Please try the following code snippet:
BEGIN CODE
private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
this.tabControl1.Visible = false;
}
private void treeView2_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
this.tabControl1.Visible = true;
}
END CODE
I hope this helps .
Regards,
John Adams
ComponentOne LLC
|
|
|
|
|
Thanks, but I don't need any help, you might want to reply to the original poster .
Standards are great! Everybody should have one!
|
|
|
|
|
i think he was in hurry
TVMU^P[[IGIOQHG^JSH`A#@`RFJ\c^JPL>;"[,*/|+&WLEZGc`AFXc!L
%^]*IRXD#@GKCQ`R\^SF_WcHbORY87??6?N8?BcRAV\Z^&SU~%CSWQ@#2
W_AD`EPABIKRDFVS)EVLQK)JKSQXUFYK[M`UKs*$GwU#(QDXBER@CBN%
Rs0~53%eYrd8mt^7Z6]iTF+(EWfJ9zaK-i?TV.C\y<p?jxsg-b$f4ia>
--------------------------------------------------------
128 bit encrypted signature, crack if you can
|
|
|
|
|
Does anybody know a way that I can perform the deserialization of the xml into a List<T> that doesn't require me to create a class that inherits List<> and overrides the serialization?
My current predicament is that I have the following Xml doc:
<Outstanding>
<WorkItem UserId="2014C908-1FD3-447C-B6EA-56DDB1602E45">
<TotalItems>74</TotalItems>
<Tables>
<Table Id="0">
<Name>Table0</Name>
<ItemCount>74</ItemCount>
</Table>
</Tables>
</WorkItem>
<WorkItem UserId="E40B31E5-E342-424C-A12B-8EF2D819DB3E">
<TotalItems>41</TotalItems>
<Tables>
<Table Id="0">
<Name>Table0</Name>
<ItemCount>41</ItemCount>
</Table>
</Tables>
</WorkItem>
</Outstanding>
And I have the following class:
public class WorkItem
{
#region Member variables
private int _totalItems;
private List<WorkItemTable> _tables;
private Guid _userId;
private MembershipUser _user;
#endregion
public MembershipUser User
{
get { return _user; }
}
public int TotalItems
{
get { return _totalItems; }
}
public List<WorkItemTable> Tables
{
get { return _tables; }
}
}
As you can see the class doesn't match the Xml doc especially the User property, ideally I want to get the userId from the Xml doc and then query the Membership provider to return me the actual MembershipUser object.
I have tried using IXmlSerializable, the ReadXml specifically is:
public void ReadXml(System.Xml.XmlReader reader)
{
reader.MoveToElement();
reader.MoveToFirstAttribute();
_userId = new Guid(reader.Value);
reader.ReadToFollowing("TotalItems");
// Try and get the total items
if (!int.TryParse(reader.ReadElementString("TotalItems"), out _totalItems))
throw new SerializationException("Unable to de-serialize WorkItem due to problem with TotalItems element");
// Now we have read the specific items for the WorkItem de-serialize the tables
XmlSerializer serializer = new XmlSerializer(typeof(List<WorkItemTable> ), new XmlRootAttribute("Tables"));
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
_tables = (List<WorkItemTable> )serializer.Deserialize(reader);
}
Which works fine for a single WorkItem element but when I attempt to execute:
XmlSerializer s = new XmlSerializer(List<WorkItem> );
TextReader reader = new StringReader(xmlData);
s.Deserialize(reader);
The XmlSerializer passes a reader that iterates over all of the WorkItem elements which means I end up with only a single item in the list rather than multiple items entered in the Xml.
|
|
|
|
|
When you have a List of WorkItems, you have to call the Deserialize (which inturn calls the ReadXML) multiple times to load the complete list. You will have to iterate thru the XML Reader (thru the list of WorkItem elements serialized into a single XML file) and call the Deserialize for each WorkItem element, and add the retrived WorkItem to a list. With this logic you can finally populate the List of WorkItems loaded back from XML, into which you have previously serialized the list of WorkItems.
You can try this -
TextReader reader = new StringReader(xmlData);
System.Xml.XmlReader xmlReader = System.Xml.XmlReader.Create( reader );
List&lt;WorkItem&gt; workItemList = new List&lt;WorkItem&gt;( );
try
{
xmlReader.ReadStartElement( );
while ( ( xmlReader.MoveToContent( ) == XmlNodeType.Element &amp;&amp; xmlReader.LocalName == typeof( WorkItem ).Name ) )
{
workItemList.Add( ( WorkItem )new XmlSerializer( typeof( WorkItem ) ).Deserialize( xmlReader ) );
xmlReader.Read( );
}
}
catch (Exception ex)
{
}
finally
{
xmlReader.Close();
Reader.Close();
Reader.Dispose();
}
|
|
|
|
|
I have created an C# application to compile C# and VB code. Now I want to extend it to Visual J# as well. Is there any specific class for that(as there are CSharpCodeProvider and VBCodeProvider for C# and VB)??
Also, can I post the code for review??
modified on Tuesday, February 26, 2008 7:21 AM
|
|
|
|
|
And how is the VJSharpCodeProvider not working for you?
|
|
|
|
|