Timer Run Once,Not continuous - c#

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();
}
}
}

Related

C# Batch file output problems

I have been working on a manager application for a Minecraft server, when I run my program, the console shows and disappears, if I run it manually, it runs without and problems.
Batch file code:
java -Xmx1024M -jar craftbukkit-1.7.2-R0.3.jar -o false
My full code (MessageBoxes are in Polish, becouse im from Poland, but later i will add support for other languages):
using System;
using System.IO;
using System.Windows.Forms;
using System.Diagnostics;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public Process server;
private Boolean runServer()
{
if (!File.Exists(textBox2.Text))
{
MessageBox.Show("Brak określonej ścieżki dostępu! (" + textBox2.Text + ")", "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
Process process = new Process
{
StartInfo =
{
FileName = textBox2.Text,
//Arguments = textBox3.Text,
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = false,
}
};
process.OutputDataReceived += new DataReceivedEventHandler(server_outputDataReceived);
process.ErrorDataReceived += new DataReceivedEventHandler(server_outputDataReceived);
server = process;
if (process.Start())
return true;
else
{
MessageBox.Show("Nie można włączyć serwera!", "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}
private String ReadFile(String filename, int line)
{
StreamReader reader = new StreamReader(filename);
for (int i = 0; i < line; i++)
{
reader.ReadLine();
}
return reader.ReadLine();
}
private void ReloadOPs()
{
if (!File.Exists(textBox1.Text))
{
MessageBox.Show("Sciezka dostępu do pliku z listą graczy posiadających OP nie istnieje! (" + textBox1.Text + ")", "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
tabControl1.SelectedTab = tabPageOptions;
textBox1.SelectAll();
return;
}
String line = ReadFile(textBox1.Text, 0);
comboBox1.Items.Clear();
for (int i = 1; i < File.ReadAllLines(textBox1.Text).Length; i++)
{
if (!String.IsNullOrWhiteSpace(ReadFile(textBox1.Text, i)))
{
comboBox1.Items.Add(line);
line = ReadFile(textBox1.Text, i);
}
}
MessageBox.Show("Lista graczy z OP, została odświeżona.");
}
// OPs combobox (OPs)
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
groupBox1.Text = comboBox1.SelectedItem.ToString();
groupBox1.Visible = true;
}
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Text = Application.StartupPath.ToString() + #"\ops.txt";
ReloadOPs();
}
// Reload OPs button (OPs)
private void button1_Click(object sender, EventArgs e)
{
ReloadOPs();
}
// Save button (Options)
private void button4_Click(object sender, EventArgs e)
{
}
private void server_outputDataReceived(object sender, DataReceivedEventArgs e)
{
addConsoleMessage(e.Data.ToString(), true);
}
// Run server button (Menu)
private void button5_Click(object sender, EventArgs e)
{
if (!runServer())
return;
server.BeginOutputReadLine();
button6.Enabled = true;
}
// Stop server button (Menu)
private void button6_Click(object sender, EventArgs e)
{
if(!server.HasExited)
server.Kill();
button6.Enabled = false;
}
private void addConsoleMessage(String message, Boolean refresh)
{
listBox1.Items.Add(message);
if (refresh)
listBox1.Refresh();
}
}
}
My problem is that program crashes becouse InvaildOperationException was unhandled (listBox1.Items.Add(message) in addConsoleMessage).
External error information: Invalid operation between threads: the control 'listBox1' is accessed from a thread other than the thread it was created.
You cannot update UI form background thread. Try this
WPF
private void server_outputDataReceived(object sender, DataReceivedEventArgs e)
{
Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Normal, () =>
{
addConsoleMessage(e.Data.ToString(), true);
});
}
Update
In WinForms the Invoke/BeginInvoke methods are directly on the control objects as you can see from the docs of System.Windows.Forms.Control. So you'd have listBox1.BeginInvoke(...) for example.

Showing words in a text file via textbox?

My code simply reads the file, splits it into words and whows each word in the textbox with 0.1 seconds frequency.
I click to "button1" to get the file and split.
After I click Start_Button the program gets stuck. I can't see any problem in the code. Can anyone see it please?
My code is here;
public partial class Form1 : Form
{
string text1, WordToShow;
string[] WordsOfFile;
bool LoopCheck;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog BrowseFile1 = new OpenFileDialog();
BrowseFile1.Title = "Select a text file";
BrowseFile1.Filter = "Text File |*.txt";
BrowseFile1.FilterIndex = 1;
string ContainingFolder = AppDomain.CurrentDomain.BaseDirectory;
BrowseFile1.InitialDirectory = #ContainingFolder;
//BrowseFile1.InitialDirectory = #"C:\";
BrowseFile1.RestoreDirectory = true;
if (BrowseFile1.ShowDialog() == DialogResult.OK)
{
text1 = System.IO.File.ReadAllText(BrowseFile1.FileName);
WordsOfFile = text1.Split(' ');
textBox1.Text = text1;
}
}
private void Start_Button_Click(object sender, EventArgs e)
{
timer1.Interval = 100;
timer1.Enabled = true;
timer1.Start();
LoopCheck = true;
try
{
while (LoopCheck)
{
foreach (string word in WordsOfFile)
{
WordToShow = word;
Thread.Sleep(1000);
}
}
}
catch
{
Form2 ErrorPopup = new Form2();
if (ErrorPopup.ShowDialog() == DialogResult.OK)
{
ErrorPopup.Dispose();
}
}
}
private void Stop_Button_Click(object sender, EventArgs e)
{
LoopCheck = false;
timer1.Stop();
}
private void timer1_Tick(object sender, EventArgs e)
{
textBox1.Text = WordToShow;
}
}
}
Instead of Thread.Sleep(1000); use async/await feature with Task.Delay in order to keep your UI responsible:
private async void Start_Button_Click(object sender, EventArgs e)
{
timer1.Interval = 100;
timer1.Enabled = true;
timer1.Start();
LoopCheck = true;
try
{
while (LoopCheck)
{
foreach (string word in WordsOfFile)
{
WordToShow = word;
await Task.Delay(1000);
}
}
}
catch
{
Form2 ErrorPopup = new Form2();
if (ErrorPopup.ShowDialog() == DialogResult.OK)
{
ErrorPopup.Dispose();
}
}
}

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.

How to start a long running process in a separate thread

ok here we go last part almost done! one error to go hmmmmm.
This is using the suggestion and is complaining about delegates i think.
using System;
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
pictureBox2.Visible = false;
}
private void button1_Click(object sender, EventArgs e)
{
Task t = new Task(() => GetsalesFigures(accCollection.Text));
t.Start();
}
private void SetPictureBoxVisibility(bool IsVisible)
{
if (pictureBox2.InvokeRequired)
{
pictureBox2.Invoke(new Action<bool>(SetPictureBoxVisibility), new Object[] { IsVisible });
}
else
{
pictureBox2.Visible = IsVisible;
}
}
private void SetCheckBoxValue(bool IsChecked)
{
if (checkBox1.InvokeRequired)
{
pictureBox2.Invoke(new Action<bool>(SetCheckBoxValue), new Object[] { IsChecked });
}
else
{
checkBox1.Checked = IsChecked;
}
}
private void AddItem(string value)
{
if (accCollection.InvokeRequired)
{
accCollection.Invoke(new Action<string>(AddItem), new Object[] { value });
}
else
{
accCollection.Items.Add(value);
}
}
private void Form1_Load(object sender, EventArgs e)
{
AutofillAccounts();
}
private void GetsalesFigures(string Acct)
{
try
{
string myConn = "Server=af" +
"Database=sdfta;" +
"uid=busdf4;" +
"pwd=drsdft;" +
"Connect Tisdf=120;";
string acct;// test using 1560
SqlConnection conn = new SqlConnection(myConn);
SqlCommand Pareto = new SqlCommand();
BindingSource bindme = new BindingSource();
SqlDataAdapter adapt1 = new SqlDataAdapter(Pareto);
DataSet dataSet1 = new DataSet();
DataTable table1 = new DataTable();
//CREATE THE THREAD
//acct = accCollection.Text;
acct = Acct;
string fromDate = this.dateTimePicker1.Value.ToString("MM/dd/yyyy");
string tooDate = this.dateTimePicker2.Value.ToString("MM/dd/yyyy");
Pareto.Connection = conn;
Pareto.CommandType = CommandType.StoredProcedure;
Pareto.CommandText = "dbo.GetSalesParetotemp";
Pareto.CommandTimeout = 120;
Pareto.Parameters.AddWithValue("#acct", acct);
Pareto.Parameters.AddWithValue("#from", fromDate);
Pareto.Parameters.AddWithValue("#too", tooDate);
//pictureBox2.Visible = true;
//checkBox1.Checked = true;
SetCheckBoxValue(true);
SetPictureBoxVisibility(true);
adapt1.Fill(dataSet1, "Pareto");
//checkBox1.Checked = false;
//pictureBox2.Visible = false;
SetCheckBoxValue(false);
SetPictureBoxVisibility(true);
this.dataGridView1.AutoGenerateColumns = true;
this.dataGridView1.DataSource = dataSet1;
this.dataGridView1.DataMember = "Pareto";
dataGridView1.AutoResizeColumns(
DataGridViewAutoSizeColumnsMode.AllCells);
SetPictureBoxVisibility(true);
acct = Acct;
}
catch (Exception execc)
{
MessageBox.Show("Whoops! Seems we couldnt connect to the server!"
+ " information:\n\n" + execc.Message + execc.StackTrace,
"Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
}
private void AutofillAccounts()
{
//get customers list and fill combo box on form load.
try
{
string myConn1 = "Server=sdf33;" +
"Database=sdft;" +
"uid=bdf4;" +
"pwd=ddft;" +
"Connect Timeout=6000;";
SqlConnection conn1 = new SqlConnection(myConn1);
conn1.Open();
SqlCommand accountFill = new SqlCommand("SELECT keycode FROM dbo.Customer", conn1);
SqlDataReader readacc = accountFill.ExecuteReader();
while (readacc.Read())
{
AddItem(readacc.GetString(0).ToString());
}
conn1.Close();
}
catch(Exception exc1)
{
MessageBox.Show("Whoops! Seems we couldnt connect to the server!"
+ " information:\n\n" + exc1.Message + exc1.StackTrace,
"Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
}
}
}
not sure where the changes should be made, shouldnt it be in the account method now?
You have many problems in your code:
The call to Application.Run() is a blocking call. It won't return until you close your form.
So your thread starts when your application is about to exit.
Just start your thread before calling Run():
Thread aniSql = new Thread(new ThreadStart(getSalesFigures));
aniSql.Start();
Application.Run(new Form1());
A Tip: Start using the debugger and step through your code. You would have noticed that your thread function is never reached.
You create a second instance of Form1 in the function GetSalesFigures. You have to use the existing instance when polling the state of the checkbox.
Your thread will perform only a single check and then it returns. You have to write some code in GetSalesFigures to wait for the user to check the checkbox. Otherwise nothing will happen.
You can use a ManualResetEvent for waiting on an event:
ManualResetEvent mre = new ManualResetEvent(false);
void YourThreadFunc() {
// Wait until someone signals mre
mre.WaiteOne();
// start sql
...
}
In your form:
private void button1_Click(object sender, EventArgs e)
{
// trigger the WaitHandle to signal the waiting thread
mre.Set();
}
Fixed some minor spelling errors, didn't have a compiler at hand back then.
To your last error: Just provide the accCollection.Text as parameter to your method. See the updated button1_Click() and GetsalesFigures(String Acct).
This is how my Partial Class : Form looks like
public Form1()
{
InitializeComponent();
pictureBox2.Visible = false;
}
private void Form1_Load(object sender, EventArgs e)
{
AutofillAccounts();
}
private void button1_Click(object sender, EventArgs e)
{
checkBox1.Checked = true;
string acct = accCollection.Text;
Task t = new Task(() => GetsalesFigures(acct));
t.Start();
}
private void GetsalesFigures(String Acct)
{
// (...)
//pictureBox2.Visible = true; use SetPictureBoxVisibility
SetPictureBoxVisibility(true);
//checkBox1.Checked = true; use SetCheckBoxValue
SetCheckBoxValue(true);
// (...)
SetCheckBoxValue(false);
SetPictureBoxVisibility(false);
// (...)
acct = Acct;
// (...)
SetDataGrid(true, dataSet1, "Pareto", DataGridViewAutoSizeColumnsMode.AllCells);
}
private void AutofillAccounts()
{
// (...)
while (readacc.Read())
{
AddItem(readacc.GetString(0).ToString());
}
}
private void SetCheckBoxValue(bool IsChecked)
{
if (checkBox1.InvokeRequired)
{
pictureBox2.Invoke(new Action<bool>(SetCheckBoxValue), new Object[] { IsChecked });
}
else
{
checkBox1.Checked = IsChecked;
}
}
private void SetPictureBoxVisibility(bool IsVisible)
{
if (pictureBox2.InvokeRequired)
{
pictureBox2.Invoke(new Action<bool>(SetPictureBoxVisibility), new Object[] { IsVisible });
}
else
{
pictureBox2.Visible = IsVisible;
}
}
// Your latest comment
private void AddItem(string value)
{
if (accCollection.InvokeRequired)
{
accCollection.Invoke(new Action<string>(AddItem), new Object[] { value });
}
else
{
accCollection.Items.Add(value);
}
}
private void SetDataGrid(bool AutoGenerateColumns, Object DataSource, String DataMember, DataGridViewAutoSizeColumnsMode Mode)
{
if (this.dataGridView1.InvokeRequired)
{
this.dataGridView1.Invoke(new Action<bool, Object, String, DataGridViewAutoSizeColumnsMode>(SetDataGrid),
AutoGenerateColumns, DataSource, DataMember, Mode);
}
else
{
this.dataGridView1.AutoGenerateColumns = AutoGenerateColumns;
this.dataGridView1.DataSource = DataSource;
this.dataGridView1.DataMember = DataMember;
dataGridView1.AutoResizeColumns(Mode);
}
}
And Program.cs
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
To summary your problem: You have to encapsulate all control-related updates you want to call from another thread than the main thread just like I did it with the two controls.
Some ressources you might want to check for multithreading / tasks
http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.aspx
http://blogs.msdn.com/b/pfxteam/archive/2009/06/30/9809774.aspx

C#, passing events doesn't work

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.

Categories