C#, passing events doesn't work - c#

I have this example code that DOES work.
main form:
FileTransferManager fm = new FileTransferManager();
...
public FrmMain()
{
InitializeComponent();
...
fm.OnFile += fm_OnFile;
}
...
void fm_OnFile(object sender, FileTransferEventArgs e)
{
var recvFile = new FrmReceiveFile(fm, e);
recvFile.Show();
e.Accept = true;
}
and FrmReceiveFile:
public partial class FrmReceiveFile : Form
{
private FileTransferManager fm;
private FileTransferEventArgs ftea;
public FrmReceiveFile(FileTransferManager ftm, FileTransferEventArgs fea)
{
InitializeComponent();
fm = ftm;
ftea = fea;
Text = "File transfer: " + ftea.Jid;
lblSize.Text = Util.HumanReadableFileSize(ftea.FileSize);
lblFileName.Text = ftea.Filename;
lblDescription.Text = ftea.Description;
fm.OnError += fm_OnError;
fm.OnEnd += fm_OnEnd;
fm.OnStart += fm_OnStart;
fm.OnProgress += fm_OnProgress;
}
void fm_OnStart(object sender, FileTransferEventArgs e)
{
MessageBox.Show("file transfer started"); ///// THIS APPEARS & EVERYTHING WORKS!
if (e.Sid != ftea.Sid)
return;
}
...
And here is my code, all in one form, yet somehow it does not work.
public partial class Form1 : Form
{
private string sid = "";
FileTransferManager fmout = new FileTransferManager(); //// this FileTransferManager is for outgoing files
FileTransferManager fmin = new FileTransferManager(); //// this FileTransferManager is for incomeing files
FileTransferEventArgs fta = new FileTransferEventArgs();
Jid _jid = new Jid();
public Form1()
{
InitializeComponent();
fmout.OnError += fmout_OnError;
fmout.OnEnd += fmout_OnEnd;
fmout.OnStart += fmout_OnStart;
fmout.OnProgress += fmout_OnProgress;
fmout.XmppClient = xmppClient;
fmin.XmppClient = xmppClient;
fmin.OnFile += fmin_OnFile;
fmin.OnEnd += fmin_OnEnd;
fmin.OnStart += fmin_OnStart;
fmin.OnProgress += fmin_OnProgress;
}
////////////////////////////////////////////////////////////////////////////////////////////
void fmin_OnFile(object sender, FileTransferEventArgs e)
{
DisplayEvent("INCOMING FILE: " + e.Filename + " - " + e.FileSize); ///// THIS APPEARS CORRECTLY
e.Accept = true;
fta = e;
}
void fmin_OnStart(object sender, FileTransferEventArgs e) /// THIS WON'T START! :(
{
MessageBox.Show("Incoming file!"); /// THIS WON'T START! :(
if (e.Sid != fta.Sid)
return;
}
Looks like e.Accept = true; does not launch fmin_OnStart ... any ideas what might be the problem?
Thanks!

The difference (that can be made out from the code you have shared) in the two pieces of code is that in the first one you are registering the "fm.OnStart += fm_OnStart" event when your "OnFileHandler" is called, while in the other one (not working) you are doing that upfront, even when your OnFileHandler is not called.
Though, as an user of FileTransferManager, i dont think that should matter.
Still, you can try the same thing in the second code.. so do it as below.
void fmin_OnFile(object sender, FileTransferEventArgs e)
{ fmin.OnStart += fmin_OnStart;
DisplayEvent("INCOMING FILE: " + e.Filename + " - " + e.FileSize);
e.Accept = true; fta = e; }
If that works, i would rather question the programmer of FileTransferManager.

Related

How to move a function to a separate assembly from the interface [Error]

I am currently working on a file copying facility that allows me to select a source and a destination for the folders to be copied from and to. A progress bar is displayed after the user clicks on Copy.
The only issue is that All of my functions reside in one file which is form1.cs (as follows)
namespace CopyFacility
{
public partial class Form1 : Form
{
BackgroundWorker background = new BackgroundWorker();
FolderBrowserDialog folderBrowser = new FolderBrowserDialog();
OpenFileDialog openFile = new OpenFileDialog();
public Form1()
{
InitializeComponent();
background.WorkerSupportsCancellation = true;
background.WorkerReportsProgress = true;
background.DoWork += Background_DoWork;
background.RunWorkerCompleted += Background_RunWorkerCompleted;
background.ProgressChanged += Background_ProgressChanged;
}
string inputFile = null;
string outputFile = null;
private void CopyFile(string source, string destination, DoWorkEventArgs e)
{
FileStream fsOut = new FileStream(destination, FileMode.Create);
FileStream fsIn = new FileStream(source, FileMode.Open);
byte[] buffer = new byte[1048756];
int readBytes;
while((readBytes = fsIn.Read(buffer,0,buffer.Length)) > 0)
{
if(background.CancellationPending)
{
e.Cancel = true;
background.ReportProgress(0);
fsIn.Close();
fsOut.Close();
return;
}
else
{
fsOut.Write(buffer, 0, readBytes);
background.ReportProgress((int) (fsIn.Position * 100 / fsIn.Length));
}
fsOut.Write(buffer, 0, readBytes);
background.ReportProgress((int)(fsIn.Position * 100 / fsIn.Length));
}
fsIn.Close();
fsOut.Close();
}
private void Background_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
fileProgressBar.Value = e.ProgressPercentage;
}
private void Background_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if(e.Cancelled)
{
fileProgressBar.Visible = true;
lblMessage.Visible = true;
lblMessage.Text = "The process has been cancelled";
}
else
{
fileProgressBar.Visible = true;
lblMessage.Visible = true;
lblMessage.Text = "The process has been completed";
}
}
private void Background_DoWork(object sender, DoWorkEventArgs e)
{
CopyFile(inputFile, outputFile + #"\" + Path.GetFileName(inputFile),e);
}
private void btnCancel_Click(object sender, EventArgs e)
{
background.CancelAsync();
}
private void btnCopy_Click(object sender, EventArgs e)
{
if(background.IsBusy)
{
lblProgress.Visible = true;
}
else
{
fileProgressBar.Visible = true;
background.RunWorkerAsync();
}
}
private void btnSource_Click(object sender, EventArgs e)
{
if(openFile.ShowDialog() == DialogResult.OK )
{
inputFile = openFile.FileName;
btnSource.Text = inputFile;
}
}
private void btnDestination_Click(object sender, EventArgs e)
{
if (folderBrowser.ShowDialog() == DialogResult.OK)
{
outputFile = folderBrowser.SelectedPath;
btnDestination.Text = outputFile + #"\" + Path.GetFileName(inputFile);
}
}
}
}
I was wondering how I could go about putting the function "CopyFile" into it's own class that can be called whenever the button is clicked?
When I try creating a new class method and inserting the functions related to the copying function into a new class "CopyFunction.cs" , I get a following error from the code "InitializingComponent();" as follows
public CopyPresenter(BackgroundWorker background, FolderBrowserDialog folderBrwoser, OpenFileDialog openFile)
{
InitializeComponent();
background.WorkerSupportsCancellation = true;
background.WorkerReportsProgress = true;
background.DoWork += Background_DoWork;
background.RunWorkerCompleted += Background_RunWorkerCompleted;
background.ProgressChanged += Background_ProgressChanged;
}
The error says that the "InitializeComponent" doesn't exist in the current context.

C# textfile only contains last string written to file with StreamWriter

I'm writing a Chat Program in C# (Windows Forms Application), the solution contains to projects which both consist of one form ( see picture ). While sending messages to each other works, I'm trying to record the conversation session in a .txt file named dateTime.txt using StreamWriter. Creating the file if it does not exist yet works, but whenever I open the text file, it only contains the last string that was written to it instead of containing the whole "conversation".
Does anybody know how to fix this?
This is the code of one of the forms, but since the forms do exactly the same, the code is the same too so i'm only posting the code of one Form. Would be great if somebody knows what I have to change so the whole conversation is recorded in the text file.
namespace Assignment3Client
{
public partial class Chat : Form
{
NamedPipeClientStream clientPipe = new NamedPipeClientStream("pipe2");
NamedPipeServerStream serverPipe = new NamedPipeServerStream("pipe1");
string msg = String.Empty;
string msgStr;
string name;
byte[] ClientByte;
public Chat()
{
InitializeComponent();
}
private void btnStartChat_Click(object sender, EventArgs e)
{
this.Text = "Waiting for a connection....";
if (txtBoxName.Text.Length == 0)
{
MessageBox.Show("please enter a name first.");
}
else
{
name = txtBoxName.Text;
clientPipe.Connect();
serverPipe.WaitForConnection();
if (serverPipe.IsConnected)
{
this.Text = "You are connected, " + name + "!";
btnStartChat.Enabled = false;
btnSend.Enabled = true;
txtBoxMsg.Enabled = true;
txtBoxMsg.Focus();
receiveWorker.RunWorkerAsync();
}
}
}
private void btnSend_Click(object sender, EventArgs e)
{
msg = "[" + name + ": " + DateTime.Now + "] " + txtBoxMsg.Text;
txtBoxChat.AppendText(msg + "\n");
FileWriter(msg);
sendWorker.RunWorkerAsync(msg); //start backgroundworker and parse msg string to the dowork method
txtBoxMsg.Clear();
txtBoxMsg.Focus();
}
private void sendWorker_DoWork(object sender, DoWorkEventArgs e)
{
Byte[] msgByte = System.Text.Encoding.GetEncoding("windows-1256").GetBytes(msg);
serverPipe.Write(msgByte, 0, msg.Length);
}
private void receiveWorker_DoWork(object sender, DoWorkEventArgs e)
{
ClientByte = new Byte[1000];
int i;
for (i = 0; i < ClientByte.Length; i++)
{
ClientByte[i] = 0x20;
}
clientPipe.Read(ClientByte, 0, ClientByte.Length);
msgStr = System.Text.Encoding.GetEncoding("windows-1256").GetString(ClientByte);
receiveWorker.ReportProgress(i, msgStr);
}
private void receiveWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if ((string)e.UserState == String.Empty)
{ MessageBox.Show("no message"); }
else
{
string message = (string)e.UserState;
txtBoxChat.AppendText(message);
FileWriter(message);
txtBoxChat.BackColor = System.Drawing.Color.DarkBlue;
txtBoxChat.ForeColor = System.Drawing.Color.White;
}
}
private void receiveWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (clientPipe.IsConnected)
{
receiveWorker.RunWorkerAsync();
}
else
{
txtBoxMsg.Enabled = false;
btnSend.Enabled = false;
MessageBox.Show("Connection lost");
}
}
private void Chat_Activated(object sender, EventArgs e)
{
txtBoxChat.BackColor = new System.Drawing.Color();
txtBoxChat.ForeColor = new System.Drawing.Color();
}
private void exitMenuStrip_Click(object sender, EventArgs e)
{
this.Close();
}
private void conMenuSrip_Click(object sender, EventArgs e)
{
}
private void errMenuStrip_Click(object sender, EventArgs e)
{
}
public void FileWriter(string message)
{
string path = #"C:\Users\selin\Documents\TAFE\Term 3\dateTime.txt";
FileStream conLog;
if (!File.Exists(path))
{
conLog = new FileStream(path, FileMode.Create);
}
else
{
conLog = new FileStream(path, FileMode.Open);
}
StreamWriter writer = new StreamWriter(conLog);
writer.WriteLine(message);
writer.AutoFlush = true;
writer.Close();
MessageBox.Show("written to file" + message);
}
}
}
in FileWriter(string message) change
conLog = new FileStream(path, FileMode.Open);
to
conLog = new FileStream(path, FileMode.Append);

Timer Run Once,Not continuous

I apologize for the use of language translation
I want to run the timer once. Next blogger.I'm saving it to the database.
Ongoing notification..One in 4 seconds
timer1 :Enabled ,Interval :4000
MyCode:
public bool InternetKontrol()
{
try
{
System.Net.Sockets.TcpClient kontrol_client = new System.Net.Sockets.TcpClient("www.google.com.tr", 80);
return true;
}
catch (Exception)
{
label1.Text = "";
return false;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (InternetKontrol()==false)
{
NetGelenGiden ngg = new NetGelenGiden();
ngg.GidenZaman = "Net Gitti " + DateTime.Now.ToLongTimeString().ToString();
ngg.GelenZaman = "";
dat.NetGelenGidens.Add(ngg);
dat.SaveChanges();
notifyIcon1.Icon = SystemIcons.Information;
notifyIcon1.ShowBalloonTip(3000, "Net Durum", "Net Gitti " + DateTime.Now.ToLongTimeString().ToString(),ToolTipIcon.Info);
notifyIcon1.Visible = true;
label2.Text ="Net Gitti "+ DateTime.Now.ToLongTimeString().ToString();
}
I think you are defining Timer control in a Windows Forms (that's because you don't put the timer1 declaration).
At the beginning of your event timer1_Tick, disable or stop the timer:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
timer1.Start();
}
private bool InternetKontrol() { /* your code */ }
public bool flagInternetService = true;
private void timer1_Tick(object sender, EventArgs e)
{
var newResult = InternetKontrol();
var warn = false;
if (flagInternetService != newResult){
if (newResult == false) warn = true;
flagInternetService = newResult;
}
if (warn)
{
/* your code warning */
label2.Text = DateTime.Now.ToLongTimeString();
}
}
}

Copy text from row in GridEX

Using Janus GridEx control, Visual C#. I have a timer that updates the grid every 3 min through a stored function on the DB. How can I double click a specific row and have it show within a multiple line textbox with the text of the 4 cells in the grid?
Been at this for 4 days and am going NUTS!!!
Starting form:
public DSC_Mon()
{
InitializeComponent();
Caller = new DSCU_SvcConsumer.MTCaller();
dsZA = new DataSet();
dsOut = new DataSet();
this.gridEXMon.DoubleClick += new System.EventHandler(this.gridEXMon_DoubleClick);
}
private void DSC_Mon_Load(object sender, EventArgs e)
{
timer1.Enabled = true;
}
private void LoadData()
{
if (!dsZA.Tables.Contains("Query"))
{
DataTable dtZA = dsZA.Tables.Add("Query");
dtZA.Columns.Add("str");
dtZA.Rows.Add(string.Format(#"exec MON_GetStatus"));
}
//dtZA.Rows.Add(string.Format(#"select * from am_company"));
dsOut.Clear();
dsOut.Merge(Caller.CallRequest("ZuluAction", dsZA));
if (gridEXMon.DataSource == null)
{
gridEXMon.DataSource = dsOut;
gridEXMon.DataMember = "Table";
}
//gridEXMon.RetrieveStructure();
}
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Enabled = false;
LoadData();
timer1.Enabled = true;
}
private void gridEXMon_DoubleClick(object sender, EventArgs e)
{
ReportInfo report = new ReportInfo();
report.ShowDialog();
}
}
}
Popup Box:
public ReportInfo()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
string value = "System: " + Environment.NewLine + systemNameTextBox.Text + Environment.NewLine +
Environment.NewLine + "Manager: " + Environment.NewLine + contactName1TextBox.Text +
Environment.NewLine + Environment.NewLine + "Function Name: " + Environment.NewLine +
functionNameTextBox.Text;
Clipboard.SetText(value);
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtpaddress");
mail.From = new MailAddress("emailaddress");
mail.To.Add("emailaddress");
mail.Subject = "Test Mail";
mail.Body = value;
SmtpServer.Port = 25;
SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
SmtpServer.EnableSsl = false;
SmtpServer.Send(mail);
MessageBox.Show(" Report Information sent to Service Support Group");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
You need to use the RowDoubeClick event of the GridEX.
This is how to use it:
private void gridEXMon_RowDoubleClick(object sender, Janus.Windows.GridEX.RowActionEventArgs e)
{
if (e.Row.RowIndex < 0)
return;
int BillID = Convert.ToInt32(e.Row.Cells["Cell1"].Value);
String BillID = Convert.ToString(e.Row.Cells["Cell2"].Value);
Decimal BillID = Convert.ToDecimal(e.Row.Cells["Cell3"].Value);
int BillID = Convert.ToInt32(e.Row.Cells["Cell4"].Value);
ReportInfo report = new ReportInfo();
// Here you need to pass the 4 cell values to your Pop up Dialog
report.ShowDialog();
}

Why this application is taking so much of memory?

So my problem is, i created one app for my personal use which fetch the html pages from some sites and then display it in a web browser after some alteration. Every thing is working fine but what perturbed me is the memory that it is taking. After querying for 3-4 terms, memory usage reaches to approximate 300-400 mb.
Some relevant code from the app is
void sentenceBox_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
GC.Collect();
}
HtmlDocument hd;
Word w=new Word();
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
status.Text = "Processing english req..";
if (checkInHis(queryTxt.Text))
{
sentenceBox.AllowNavigation = true;
richTextBox1.Text = w.engDefinition;
sentenceBox.DocumentText = w.engDefinition;
status.Text = "Word found in History.DONE!";
button1.Enabled = true;
return;
}
if (w == null || w.engWordProp != queryTxt.Text)
{
w.engWordProp=queryTxt.Text;
w.loadEngDefn();
w.engDefnLoadedEvent += new Word.engDefnLoaded(w_engDefnLoadedEvent);
return;
}
w.loadEngDefn();
w.engDefnLoadedEvent += new Word.engDefnLoaded(w_engDefnLoadedEvent);
}
void w_engDefnLoadedEvent(Word sender, EventArgs data)
{
sentenceBox.AllowNavigation = true;
sentenceBox.DocumentText = sender.engDefinition;
sender.engDefnLoadedEvent -= w_engDefnLoadedEvent;
button1.Enabled = true;
}
private void addToHistory(Word w)
{
status.Text = "Saving offline...";
if (!checkInHis(w.engWordProp))
{
history.Add(w);
// label1.Text = w.engWordProp + " saved in localdb. Database size: " + history.Count;
w = null;
}
else
{
// label1.Text = w.engWordProp + " Skipped. Database size: " + history.Count;
}
}
private Boolean checkInHis(string p)
{
status.Text = "checking offline storage...";
foreach (Word item in history)
{
if (item.engWordProp == p)
{
status.Text = "Word found in history.";
w = item;
return true;
}
}
status.Text = "Not found in offline database...";
return false;
}
private void sentenceBox_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
((WebBrowser)sender).AllowNavigation = false;
}
private void button2_Click_1(object sender, EventArgs e)
{
button2.Enabled = false;
status.Text = "Requesting hindi definition...";
if (checkInHis(queryTxt.Text))
{
sentenceBox.AllowNavigation = true;
sentenceBox.DocumentText = w.hindiDef;
status.Text = "DONE!";
button2.Enabled = true;
return;
}
if (w == null || w.engWordProp != queryTxt.Text)
{
w.engWordProp=queryTxt.Text;
w.loadHinDefn();
w.HindiDefLoadedEvent += new Word.hindiDefLoaded(w_HindiDefLoadedEvent);
return;
}
w.loadHinDefn();
w.HindiDefLoadedEvent += new Word.hindiDefLoaded(w_HindiDefLoadedEvent);
}
void w_HindiDefLoadedEvent(Word sender, EventArgs data)
{
sentenceBox.AllowNavigation = true;
sentenceBox.DocumentText = sender.hindiDef;
button2.Enabled = true;
sender.HindiDefLoadedEvent -= w_HindiDefLoadedEvent;
}
private void button3_Click(object sender, EventArgs e)
{
button3.Enabled = false;
saveWord(w);
button3.Enabled = true;
}
private void saveWord(Word w)
{
if (w.hindiDef == "")
{
w.loadHinDefn();
w.HindiDefLoadedEvent += new Word.hindiDefLoaded(w_HindiDefLoadedEventforHindiSave);
}
if (w.engDefinition == "")
{
w.loadEngDefn();
w.engDefnLoadedEvent += new Word.engDefnLoaded(w_engDefnLoadedEventforEnglishSave);
}
addToHistory(w);
}
void w_HindiDefLoadedEventforHindiSave(Word sender, EventArgs data)
{
sender.HindiDefLoadedEvent -= w_HindiDefLoadedEvent1;
sender.HindiDefLoadedEvent -= w_HindiDefLoadedEventforHindiSave;
}
void w_engDefnLoadedEventforEnglishSave(Word sender, EventArgs data)
{
sender.engDefnLoadedEvent -= w_engDefnLoadedEventforEnglishSave;
sender.engDefnLoadedEvent -= w_engDefnLoadedEventforEnglishSave;
}
void w_HindiDefLoadedEvent1(Word sender, EventArgs data)
{
saveWord(sender);
sender.HindiDefLoadedEvent -= w_HindiDefLoadedEvent1;
}
void w_engDefnLoadedEvent1(Word sender, EventArgs data)
{
sender.loadHinDefn();
sender.HindiDefLoadedEvent += new Word.hindiDefLoaded(w_HindiDefLoadedEvent1);
sender.engDefnLoadedEvent -= w_engDefnLoadedEvent1;
}
void initWord(String query)
{
queryTxt.Text = query;
w.engWordProp=queryTxt.Text;
w.loadEngDefn();
w.loadHinDefn();
w.engDefnLoadedEvent += new Word.engDefnLoaded(w_engDefnLoadedEvent);
w.HindiDefLoadedEvent += new Word.hindiDefLoaded(w_HindiDefLoadedEvent);
}
Word class
public Word(string q)
{
wb1 = new WebBrowser();
wb2=new WebBrowser();
engWord = q;
hindiDef = "";
engDefinition = "";
flagE = false;
flagH = false;
engUrl = "http://oxforddictionaries.com/definition/english/" + q + "?q=" + q;
hindiUrl = "http://dict.hinkhoj.com/hindi-dictionary.php?word=" + q;
wb1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wb_DocumentCompleted); ;
wb2.DocumentCompleted+=new WebBrowserDocumentCompletedEventHandler(wb_DocumentCompleted);
}
public delegate void engDefnLoaded(Word sender, EventArgs data);
public event engDefnLoaded engDefnLoadedEvent;
protected void onEngDefnLoadCompleated(Word sender, EventArgs data)
{
if (engDefnLoadedEvent!=null)
{
engDefnLoadedEvent(this,data);
}
}
public void loadEngDefn()
{
if (this.engDefinition=="")
{
// wb1 = new WebBrowser();
wb1.ScriptErrorsSuppressed = true;
wb1.Url = new Uri(this.engUrl);
}
else
{
if (engDefnLoadedEvent!=null)
{
engDefnLoadedEvent(this, new EventArgs());
}
}
}
public void loadHinDefn() {
if (this.hindiDef=="")
{
// wb2 = new WebBrowser();
wb2.ScriptErrorsSuppressed = true;
wb2.Url = new Uri(this.hindiUrl);
}
else
{
if (HindiDefLoadedEvent!=null)
{
HindiDefLoadedEvent(this, new EventArgs());
}
}
}
[NonSerialized]
HtmlDocument hd;
void wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (((WebBrowser)sender).ReadyState == WebBrowserReadyState.Complete)
{
hd = ((WebBrowser)sender).Document;
if (e.Url.ToString() == this.hindiUrl)
{
parsePage(hd.GetElementById("maint"), "hindi");
((WebBrowser)sender).DocumentCompleted -= wb_DocumentCompleted;
sender = null;
}
else
{
parsePage(hd.GetElementById("entryPageContent"), "eng");
((WebBrowser)sender).DocumentCompleted -= wb_DocumentCompleted;
sender = null;
}
}
}
private void parsePage(HtmlElement hd, string lan)
{
HtmlElementCollection he;
if (lan == "eng")
{
he = hd.GetElementsByTagName("section");
foreach (HtmlElement item in he)
{
this.engDefinition += item.InnerHtml + "<br>";
}
flagE = true;
engDefnLoadedEvent(this, new EventArgs());
wb1 = null;
wb1.Dispose();
return;
}
else
{
he = hd.GetElementsByTagName("div");
foreach (HtmlElement item in he)
{
if (item.GetAttribute("itemprop") == "itemListElement")
{
this.hindiDef += item.GetElementsByTagName("div")[0].InnerHtml + "<br>";
}
}
flagH = true;
HindiDefLoadedEvent(this,new EventArgs());
wb2 = null;
wb2.Dispose();
return;
}
}
Question: How to remove this memory leak issue ?
sample pic
After query 25 words.
First I'd like to point out that just because your application uses 300 - 400 MB of memory doesn't necessarily mean that you have a memory leak. Only if the memory keeps increasing with each requested page and is never released do you have a leak.
Second, in order to diagnose the problem you need to run a memory profiler. If you are using the Premium or Ultimate edition of Visual Studio, it has a memory profile feature. If not you can use either RedGate Memory Profile (14-day free trial) or similar software.
I would also add that the most common cause for leaks in .NET is the use of events where a short lived object attaches itself as an observer/handler to an event raised by a long lived object.
Well in the constructor of your Word class you have the following code:
wb1 = new WebBrowser();
wb2=new WebBrowser();
The WebBrowser class does is to instantiate some of the web browsing features of your local IE version.My guess is that WebBrowser being a part of the IE it has a high memory consumption.So imagine that you instantiate 2 WebBrowser objects for each word that you have.You could use a pool system for your WebBrowser objects, but i would replace the behavior of those with an WebClient object which is disposable.
P.S. The Garbage Collector system is a fine tuned system using GC.Collect(); it's like using a sledgehammer on your code.

Categories