My requirement is to insert item in a queue and process it but the items should be added first and after a while they should be processed (as some other things needs to be set before processing the items. Here is the coding I have done so far.
#region Variables Declarations
private Thread threadTask = null;
ConcurrentQueue<string> concurrentQueue = new ConcurrentQueue<string>();
string currentSeqNo;
string previousSeqNo = "-1";
#endregion
private void test1_Load(object sender, EventArgs e)
{
AddItems();
if (threadTask == null)
{
threadTask = new Thread(Kick);
Thread.Sleep(5000);
threadTask.Start();
}
}
private void AddItems()
{
for (Int64 i = 100000; i < 300000; i++)
{
concurrentQueue.Enqueue(i.ToString());
this.Invoke(new MethodInvoker(delegate()
{
label1.Text = i.ToString();
label1.Update();
}));
}
}
private void Kick()
{
while (true)
{
int recordCountNew = concurrentQueue.Count();
if (recordCountNew != 0)
{
RemoveItems();
}
}
}
private void RemoveItems()
{
string item;
while (concurrentQueue.TryDequeue(out item))
{
this.Invoke(new MethodInvoker(delegate()
{
label2.Text = item;
label2.Update();
}));
currentSeqNo = item; // second time does not start wil 100000
if (previousSeqNo != "-1")
{
if (long.Parse(currentSeqNo) != long.Parse(previousSeqNo) + 1)
{
Reconnect();
}
else
{
//Process item
previousSeqNo = currentSeqNo;
}
}
else
{
//Process item
previousSeqNo = currentSeqNo;
}
}
}
private void Reconnect()
{
currentSeqNo = "";
previousSeqNo = "-1";
string someItem;
while (concurrentQueue.Count > 0)
{
concurrentQueue.TryDequeue(out someItem);
}
this.Invoke(new MethodInvoker(delegate()
{
label1.Text = "";
label2.Text = "";
label1.Update();
label2.Update();
}));
AddItems();
if (threadTask == null)
{
threadTask = new Thread(Kick);
threadTask.Start();
}
}
private void button1_Click_1(object sender, EventArgs e)
{
Reconnect();
}
To reproduce the issue: Run the app and in the middle click on the button. Now the queue should again be started from 100000 but it shows the number somewhere greater than 100000.
Please advise how do I release all the resources to make a fresh start after clicking a button. Though I am setting them to default and also clearing the queue but it still shows the old values in currentSeqNo when 'RemoveItems' method is called.
What you see is a race condition between the Kick thread and the button click handler. When you press the button you execute Reconnect() in it you clean the queue and then call the AddItems() function. But all this time the Kick function tries to Dequeue and so you end up each time with an arbitrary amount of items in it. What you should do is to synchronize between these functions or prevent the Kick from executing while you are adding items.
Couple of comments:
1) You Kick() method have an infinite loop, that too without sleep. Every thread started will keep on running as you didn't have a scope for thread to come out.
You can have a member variable like bKeepRunning with default value as true. Set that variable to false in beginning of Reconnect() function. Something like:
private void Kick()
{
while (bKeepRunning)
{
int recordCountNew = concurrentQueue.Count();
if (recordCountNew != 0)
{
RemoveItems();
}
}
}
Why do you have Thread.Sleep(5000); in test1_Load()? I dont think that is needed.
I made small change in your code, something like:
private void AddItems()
{
for (Int64 i = 100000; i < 300000; i++)
{
concurrentQueue.Enqueue(i.ToString());
this.Invoke(new MethodInvoker(delegate()
{
label1.Text = i.ToString();
label1.Update();
}));
if (i < 100004)
Thread.Sleep(1000);
}
}
private void Kick()
{
while (bKeepRunning)
{
int recordCountNew = concurrentQueue.Count();
if (recordCountNew != 0)
{
RemoveItems();
}
}
}
private void Reconnect()
{
currentSeqNo = "";
previousSeqNo = "-1";
bKeepRunning = false;
threadTask = null;
string someItem;
while (concurrentQueue.Count > 0)
{
concurrentQueue.TryDequeue(out someItem);
}
this.Invoke(new MethodInvoker(delegate()
{
label1.Text = "";
label2.Text = "";
label1.Update();
label2.Update();
}));
Thread.Sleep(2000);
AddItems();
bKeepRunning = true;
if (threadTask == null)
{
threadTask = new Thread(Kick);
threadTask.Start();
}
}
It helped me to see that value is starting from 100000. You can try the same at your end.
Note: I have stopped thread and restarted after clicking on button. Hence i dont see any flaw in your code as such. It just runs fast so that you are not able to realize start values.
You should make UI thread and threadTask thread sync, just use ManualResetEventSlim Signal Construct to, like this:
static ManualResetEventSlim guard = new ManualResetEventSlim(true);
private void button1_Click_1(object sender, EventArgs e)
{
guard.Reset();
Reconnect();
guard.Set();
}
private void RemoveItems()
{
string item;
while (concurrentQueue.TryDequeue(out item))
{
guard.Wait();
//......
}
}
see:
ManualResetEventSlim Class
Related
I currently have a application that pings a list of IPs.
The user clicks a button and it continuously pings all IPS for 20 seconds..
What I want to do is click a button to stop this.
I created a function i called "Process" and it calls this process when the button is clicked.
I tried to create a bool value and while loop for when it's false and made the stop button change the bool value to true, but it doesn't seem to stop anything, in fact I can't even close the window until the ping is completed.
My code is below.
private bool _stopLoop;
private void btnPlay_Click(object sender, EventArgs e)
{
Process();
}
private void Process()
{
while (_stopLoop == false)
{
for (int i = 0; i < 20; i++)
{
foreach (DataGridViewRow dataGridView1Row in dataGridView1.Rows)
{
var count = 20;
progressBar1.Value = i * progressBar1.Maximum / count;
Application.DoEvents();
var url = dataGridView1Row.Cells[1].Value.ToString();
int timeout = 500;
Ping ping = new Ping();
PingReply pingreply = ping.Send(url, timeout);
PingReply result = null;
IPStatus status;
result = pingreply;
status = result.Status;
if (status != IPStatus.Success)
{
dataGridView1Row.Cells[0].Style.BackColor = Color.Red;
dataGridView1Row.Cells[0].Value = "Offline";
}
else
{
dataGridView1Row.Cells[0].Style.BackColor = Color.Green;
dataGridView1Row.Cells[0].Value = "Online";
}
}
}
}
}
private void btnStop_Click(object sender, EventArgs e)
{
_stopLoop = true;
}
I am only targeting the direct questions why the loops dont stop. Implementing a background thread or tasks or background worker is a better solution but not the question :)
As in my comment states, you only break out of your "infinite" loop which is the most outer loop.
The two inner loops which run over your IP's ( foreach (DataGridViewRow dataGridView1Row in dataGridView1.Rows){ [...] } as well as your "do it for 20 times" loops for (int i = 0; i < 20; i++){ [...] } need to be broken out of if you want it to stop.
this means you can change them like that:
while (_stopLoop == false)
{
for (int i = 0; i < 20; i++)
{
foreach (DataGridViewRow dataGridView1Row in dataGridView1.Rows)
{
if(_stopLoop)
return; // finish execution and jump out of all loops, or use break to jump into the for loop, but then you need to break out of it as well
/* your ping logic */
}
}
}
If you use async/await your GUI can be responsive and your requests can be concurrent at the same time:
private CancellationTokenSource pingCancellation;
private async void btnPlay_Click(object sender, EventArgs e)
{
const int pingTimeout = 500;
var pingDuration = TimeSpan.FromSeconds(20);
btnPlay.Enabled = false;
dataGridView1.ReadOnly = true;
var entries =
dataGridView1.Rows.Cast<DataGridViewRow>()
.Where(r => !r.IsNewRow)
.Select(row => new { Row = row, Hostname = row.Cells[1].Value.ToString(), Ping = new Ping() })
.ToList();
pingCancellation = new CancellationTokenSource();
pingCancellation.Token.Register(() => entries.ForEach(e => e.Ping.SendAsyncCancel()));
btnStop.Enabled = true;
pingCancellation.CancelAfter(pingDuration);
var finishTime = DateTime.UtcNow.Add(pingDuration);
try
{
while (!pingCancellation.IsCancellationRequested)
{
await Task.WhenAll(entries.Select(async e =>
{
var result = await e.Ping.SendPingAsync(e.Hostname, pingTimeout);
if (result.Status != IPStatus.Success)
{
e.Row.Cells[0].Style.BackColor = Color.Red;
e.Row.Cells[0].Value = "Offline";
}
else
{
e.Row.Cells[0].Style.BackColor = Color.Green;
e.Row.Cells[0].Value = "Online";
}
}).Concat(new[] { Task.Delay(pingTimeout, pingCancellation.Token) /*Rate limiting*/ }));
progressBar1.Value = (int)Math.Min(progressBar1.Maximum * (pingDuration - (finishTime - DateTime.UtcNow)).Ticks / pingDuration.Ticks, progressBar1.Maximum);
}
}
catch (TaskCanceledException)
{
}
btnStop.Enabled = false;
pingCancellation.Dispose();
pingCancellation = null;
foreach (var entry in entries)
{
entry.Ping.Dispose();
}
progressBar1.Value = 0;
dataGridView1.ReadOnly = false;
btnPlay.Enabled = true;
}
private void btnStop_Click(object sender, EventArgs e)
{
if (pingCancellation != null && !pingCancellation.IsCancellationRequested)
{
pingCancellation.Cancel();
}
}
I have been trying to work out why my background worker is 'finishing' its work when there is still a lot for it to do. I am actually in the process of refactoring the code for this app, so it did work in the past, but now I am unable to figure out what has gone wrong.
Specifically, the app should open Outlook and then perform a few checks. However, the background worker exits straight after Outlook is opened for no apparent reason (as you will se below there is still plenty of processing to be done).
This appears to be happening early on in the Start() method, directly after calling Process.Start() on Outlook.exe.
The code runs in this order:
calling the background worker - this was the user's choice from a radio set
....
else if (radioButton5.Checked == true)
{
textBox1.Text = "Please wait while your session restarts";
pageControl1.SelectedIndex = 10;
backgroundReset.RunWorkerAsync();
}
The do-work method
public void backgroundReset_DoWork(object sender, DoWorkEventArgs e)
{
backgroundReset.WorkerSupportsCancellation = true;
Session.Reset();
}
the reset session method starts by killing the current session ...
public static void Reset()
{
KillSession();
System.Threading.Thread.Sleep(5000);
Start();
// THE BACKGROUNDWORKER EXITS BEFORE HERE!
if (IsLoggedIn() == false)
{
return;
}
else
{
// Make sure Lync is open before finishing the process ...
var j = 0;
GetSession(Init.servers);
j = 0;
var checker = false;
checker = ProcessHandler.CheckRunning("lync.exe");
while (checker == false)
{
if (j == 100)
{
break;
}
Thread.Sleep(500);
checker = ProcessHandler.CheckRunning("lync.exe");
j++;
}
}
}
As you can see from the comment, the backgroundworder is calling RunWorkerCompleted way before the Reset() method has finished executing.
Below are the other methods called (kill, logoff, start):
KillSession logs the session of and then makes sure it is logged off
private static void KillSession()
{
if (sessionId != null)
{
LogOff();
for (int i = 0; i < 150; i++)
{
if (IsLoggedIn() == true)
{
Thread.Sleep(500);
}
else
{
break;
}
}
}
}
LogOff sends a Cmd command to log off the current session
public static void LogOff()
{
string strCmdIn = "/C LOGOFF " + sessionId + " /SERVER:" + serverName;
Cmd.Exec(strCmdIn);
}
Start() Simply opens Outlook, causing a Citrix session to also start. The app is definitely launching Outlook, but after that it doesn't reach either of the for statements - the BackgroundWorker just exits.
public static void Start()
{
Process.Start(appDataCitrix + "Outlook.exe");
for (int i = 0; i < 15; i++)
{
if (IsLoggedIn2() == false)
{
Thread.Sleep(1000);
}
else
{
break;
}
}
if (IsLoggedIn2() == false)
{
Process.Start(appDataCitrix + "Outlook.exe");
for (int i = 0; i < 10; i++)
{
if (IsLoggedIn2() == false)
{
Thread.Sleep(1000);
}
else
{
break;
}
}
}
}
Does anyone have any idea what is going on here? It is driving me crazy!
Many thanks
Update
The RunWorkerCompleted Method:
As far as my understanding goes, this has no baring on when the process will finish.
public void backgroundReset_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (Session.IsLoggedIn())
{
btnFailFinish.Visible = true;
label10.Text = Session.serverName;
pageControl1.SelectedIndex = 3;
}
else
{
pageControl1.SelectedIndex = 10;
pictureBox2.Visible = false;
textBox1.Text = "Double-click Outlook on your desktop to launch a new session.";
textBox15.Text = "Once you have done this please click Finish.";
pictureBox9.Visible = true;
}
}
This is probably because of an exception being thrown from within the start method.
You may either add a try / catch block all around this method and handle the error from within the catch, or check in the RunWorkerCompleted method if an exception occurred :
private void RunWorkerCompleted (object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
// handle your exception here
}
}
I have a probably simple question about the task factory. I have to following code:
In this task is a loop that is polling data from the RS232 and a counter that stops polling after 10 times. After this "doCollect" will be set to false.
And now comes the strange thing: The task runs repeatedly. The caller code is:
// class Main()
RS232DataAquisition _RS232DataAquisition = new RS232DataAquisition();
public override void Run()
{
System.Diagnostics.Stopwatch timeout = new System.Diagnostics.Stopwatch();
timeout.Start();
_RS232DataAquisition.Start();
while ((timeout.ElapsedMilliseconds <= (dataGatherTime_inSeconds * 1000)) && _RS232DataAquisition.DoCollect)
{
System.Threading.Thread.Sleep(100);
}
timeout.Stop();
_RS232DataAquisition.Stop();
}
Per my understanding the Run() function should start the thread and return into the while-loop waiting for the thread to finish. But it never does?!
Here's the code for ReadDataFromRS232:
// sealed class RS232DataAquisition
private bool doCollect = false;
public bool DoCollect
{
get { return doCollect; }
}
public void Start()
{
doCollect = true;
currentTask = System.Threading.Tasks.Task.Factory.StartNew(() =>
{
this.ReadDataFromRS232();
});
}
private void ReadDataFromRS232(int NumtoRead = 10)
{
var port = new System.IO.Ports.SerialPort(PortName);
int waitCount = 5;
var portExists = System.IO.Ports.SerialPort.GetPortNames().Any(x => x == PortName);
if (!portExists)
{
throw new ArgumentException("Port does not exist!");
}
while (port.IsOpen && waitCount-- > 0)
{
doCollect = false;
Wait();
}
doCollect = true;
if (!port.IsOpen)
{
port.Open();
port.NewLine = _NewLine;
port.ReadTimeout = 2000;
int number;
try { }
finally { }
port.Write("flashon\r");
while (doCollect && (_readCounter <= NumtoRead))
{
string s;
try
{
s = port.ReadLine();
}
catch
{
s = "-1";
}
int i;
if (int.TryParse(s, out i))
{
number = Convert.ToInt32(s, 10);
}
else
{
number = 0;
}
lock (thisLock) _data.Add(number);
_readCounter++;
}
port.Write("flashoff\r");
port.Close();
port.Dispose();
Wait(); Wait();
}
}
private void Wait()
{
System.Threading.Thread.Sleep(10);
System.Threading.Thread.SpinWait(1);
}
I don't get, why "ReadDataFromRS232" is beeing repeated until the timeout stops this task.
Thank you for any help :)
EDIT: Added some missing code.
As Dennis said the problem seemed to come from the missing volatile. It works now even though I have no idea why it didn't before.
Edited question totally for more understanding.
I have a count function, and I have a label who checks the current count
Here is the label
private void currentCountLabel_TextChanged(object sender, EventArgs e)
{
}
How do I make so once the label reaches as example 50, a function starts. like play sound?
//////////////////////////////
Here is the current one that #btc sources, gave me
private void currentCountLabel_Click(object sender, EventArgs e)
{
if (String.Compare(currentCountLabel.Text, "5") == 0)
{
System.Media.SoundPlayer player = new System.Media.SoundPlayer(#"sound.wav");
player.Play();
}
}
But it wont play automaticly, how do I make it to play when it reaches the number?
///////////////////////////////////////////////////////////////////////////////
private void currentCountLabel_TextChanged(object sender, EventArgs e)
{
if (String.Compare(currentCountLabel.Text, "5") == 0)
{
System.Media.SoundPlayer player = new System.Media.SoundPlayer(#"meme.wav");
player.Play();
}
}
private void writeToFile()
{
if (Properties.Settings.Default.OBSToggle)
{
if (Properties.Settings.Default.ReverseOrder)
{
File.WriteAllText(#"Count.txt", String.Format("{0} {1}", Count.ToString(), Message));
}
else
{
File.WriteAllText(#"Count.txt", String.Format("{0} {1}", Message, Count.ToString()));
}
}
private void KeyBoardHook_KeyUp(object sender, KeyEventArgs e)
{
if (Properties.Settings.Default.HotKeyEnabled && e.KeyCode == Properties.Settings.Default.HotKeyIn)
{
if (Properties.Settings.Default.SaveCount)
{
Count = Count + 1;
Properties.Settings.Default.Count = Count;
currentCountLabel.Text = Properties.Settings.Default.Count.ToString();
}
else
{
Count = Count + 1;
currentCountLabel.Text = Count.ToString();
}
Message = messageTextBox.Text;
writeToFile();
e.Handled = true;
}
if (Properties.Settings.Default.HotKeyEnabled && e.KeyCode == Properties.Settings.Default.HotKeyDe && Count != 0)
{
if (Properties.Settings.Default.SaveCount)
{
Count = Count - 1;
Properties.Settings.Default.Count = Count;
currentCountLabel.Text = Properties.Settings.Default.Count.ToString();
}
else
{
Count = Count - 1;
currentCountLabel.Text = Count.ToString();
}
Message = messageTextBox.Text;
writeToFile();
e.Handled = true;
}
}
You need a static variable to hold the current count. Initialized to zero. Then increment it each time the function executes.
Then an if statement to evaluate the count and take whatever action.
I'm trying to let a program post a bunch of text. The user enters text, the amount of messages and how fast these must be delivered. While the program is busy, the button text needs to be "Stop" instead of "Start". When you press the button to force it to stop after you've initially launched it, the text changes back to "Start", but this doesn't happen when the program stops after the given amount of messages are delivered, even though the code is in place and doesn't generate an error.
I have a feeling that this is because of the text not updating for some reason. I've tried to flush it with Invalidate() and Update(), but this isn't working. How to fix this?
Here is the code:
private void button1_Click(object sender, EventArgs e)
{
if (button1.Text == "Start")
{
isEvil = true;
button1.Text = "Stop";
Thread t = new Thread(StartTyping);
t.Start(textBox1.Text);
}
else
{
isEvil = false;
button1.Text = "Start";
}
}
private void StartTyping(object obj)
{
string message = obj.ToString();
int amount = (int)numericUpDown2.Value;
Thread.Sleep(3000);
for (int i = 0; i < amount; i++)
{
if (isEvil == false)
{
//////This does NOT work
//button1.Text = "Start";
//button1.Invalidate();
//button1.Update();
//button1.Refresh();
//Application.DoEvents();
break;
}
SendKeys.SendWait(message + "{ENTER}");
int j = (int)numericUpDown1.Value * 10;
Thread.Sleep(j);
}
}
You have four answers telling you to update UI stuff from the UI thread, but none of them address the logic flow problem with your code.
The reason why it doesn't happen is because it only happens in the for-loop when isEvil is false. When does isEvil get set to false? Only when you click "Stop", and nowhere else.
If you want the button to go back to "Start" after the thread finishes, without clicking "Stop", then you need to add code after the loop to do that, independent of the value of isEvil: (piggybacking off of VoidMain's answer)
private void StartTyping(object obj)
{
string message = obj.ToString();
int amount = (int)numericUpDown2.Value;
Thread.Sleep(3000);
for (int i = 0; i < amount; i++)
{
if (isEvil == false)
{
if (button1.InvokeRequired)
{
button1.BeginInvoke( new Action(() => { button1.Text = "Start"; }) );
}
else
{
button1.Text = "Start";
}
break;
}
SendKeys.SendWait(message + "{ENTER}");
int j = (int)numericUpDown1.Value * 10;
Thread.Sleep(j);
}
if (button1.InvokeRequired)
{
button1.BeginInvoke( new Action(() => { button1.Text = "Start"; }) );
}
else
{
button1.Text = "Start";
}
}
Now you have duplicated code, so you might want to split it off into a separate method.
You need to be on the UI thread to update the UI.
Try something called the SynchronizationContext. There are plenty of examples when you google it.
If you're in WPF or Silverlight, you could use the Dispatcher. Again, lots of examples if you search those keywords in google or StackOverflow.
You must update your controls from the UI thread. This is how you would do it for winforms.
for (int i = 0; i < amount; i++)
{
if (isEvil == false)
{
button1.Invoke(new Action(() => button1.Text = "Start"));
break;
}
SendKeys.SendWait(message + "{ENTER}");
int j = (int)numericUpDown1.Value * 10;
Thread.Sleep(j);
}
This will block till button1 get's its text updated. If you don't want it to block, replace Invoke with BeginInvoke
Your best bet is to use a BackgroundWorker. It's a bit too wieldy to add a concise example here but there's a decent tutorial from O'Reilly
Something like this (not tested) should work:
private void StartTyping(object obj)
{
string message = obj.ToString();
int amount = (int)numericUpDown2.Value;
Thread.Sleep(3000);
for (int i = 0; i < amount; i++)
{
if (isEvil == false)
{
if(button1.InvokeRequired)
{
button1.BeginInvoke( new Action(() => { button1.Text = "Start"; }) );
}
else
{
button1.Text = "Start";
}
break;
}
SendKeys.SendWait(message + "{ENTER}");
int j = (int)numericUpDown1.Value * 10;
Thread.Sleep(j);
}
}