I have data list from XML, and I want all the item in the list sent to bw_ViewJob_DoWork in my case but I only have the first data of the list in the bw_ViewJob_DoWork as a Trigger:
private void button1_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
gIP = cmbIP.Text;
timer1.Interval = 2000;
}
Trigger sends here:
private void timer1_Tick(object sender, EventArgs e)
{
string val = "";
for (int i = 0; i < listJob.Items.Count; i++)
{
val = listJob.Items[i].ToString().Substring(0, 4);
WriteLog("Job: [" + val + "] Viewed");
if (bw_ViewJob.IsBusy)
{
bw_ViewJob.CancelAsync();
WriteLog("Job: [" + val + "] Cancel");
}
else
{
bw_ViewJob.RunWorkerAsync(val);
}
}
}
And timer executes this thread infinite-loop every 30s
private void bw_ViewJob_DoWork(object sender, DoWorkEventArgs e)
{
WebRequest request;
Stream dataStream;
StreamReader reader;
string oStatus;
string responseFromServer;
gIP = cmbIP.Text;
string oURL = "https://" + gIP + "/hp/device/hp.extensibility.ec.clientservices.api?api=jobs&method=view&jobId=" + e.Argument;
byPassCert();
int i = 0;
oStatus = "pending";
WriteLog("oURL: [" + oURL + "]");
while (oStatus == "pending")
{
try
{
if (i > 0) { System.Threading.Thread.Sleep(1000); }
if (bw_ViewJob.CancellationPending)
{
e.Cancel = true;
break;
}
request = WebRequest.Create(oURL);
request.Method = "GET";
dataStream = request.GetResponse().GetResponseStream();
reader = new StreamReader(dataStream);
responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
// Get Job Info
XmlDocument oXML = new XmlDocument();
oXML.LoadXml(responseFromServer);
oStatus = oXML.DocumentElement.SelectSingleNode("Content/Job").Attributes.GetNamedItem("status").Value;
if (oStatus == "cancelled")
{
e.Cancel = true;
break;
}
i++;
}
catch (Exception eX)
{
MessageBox.Show(eX.Message, "View Job Error");
}
}
e.Result = responseFromServer;
}
private void bw_ViewJob_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
WriteLog(e.Error + ", Job Cancelled");
}
else
{
WriteLog("View Job done. JobID: " + gJobID);
WriteLog("" + e.Result + ", Still Pending, trying view another job");
}
}
I have tried List<string> and lock() but the thread just receives the first item on the list. I have tried timer loop inside the thread but I get the opposite result; the thread only has the last item on the list, I suspect.
if (bw_ViewJob.IsBusy)
{
bw_ViewJob.CancelAsync();
WriteLog("Job: [" + val + "] Cancel");
}
So I think I have to pause the loop at timer and resume again after the thread finishes without repeating the loop from the first data. How do I do that?
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Xml.Linq;
using System.Diagnostics;
using System.Management;
using System.Runtime.InteropServices;
namespace DownloadFiles
{
public partial class Form1 : Form
{
Stopwatch sw = new Stopwatch();
Stopwatch stopwatch = new Stopwatch();
string filesdirectory = "Downloaded_Files";
string mainurl = "http://www.usgodae.org/ftp/outgoing/fnmoc/models/navgem_0.5/latest_data/";
List<string> parsedlinks = new List<string>();
string path_exe = Path.GetDirectoryName(Application.LocalUserAppDataPath);
List<string> results = new List<string>();
List<string> urls = new List<string>();
string radarImageWebAddressP1;
string radarImageWebAddressP2;
public Form1()
{
InitializeComponent();
label3.Text = "";
label4.Text = "";
label5.Text = "";
label7.Text = "";
button2.Enabled = false;
button3.Enabled = false;
filesdirectory = Path.Combine(path_exe, filesdirectory);
if (!Directory.Exists(filesdirectory))
{
Directory.CreateDirectory(filesdirectory);
}
else
{
if (IsDirectoryEmpty(filesdirectory) == false)
{
button3.Enabled = true;
}
}
radarImageWebAddressP1 = "http://www.ims.gov.il/Ims/Pages/RadarImage.aspx?Row=";
radarImageWebAddressP2 = "&TotalImages=10&LangID=1&Location=";
for (int i = 0; i < 9; i++)
{
urls.Add(radarImageWebAddressP1 + i + radarImageWebAddressP2);
}
}
public bool IsDirectoryEmpty(string path)
{
return !Directory.EnumerateFileSystemEntries(path).Any();
}
private string downloadhtml(string url)
{
backgroundWorker1.ReportProgress(0, "Downloading Main Url");
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Proxy = null;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream());
string html = sr.ReadToEnd();
sr.Close();
response.Close();
StreamWriter w = new StreamWriter(path_exe + "\\page.html");
w.Write(html);
w.Close();
return html;
}
int Counter = 0;
int percentage = 0;
int total = 0;
int countfiletodownload = 0;
bool processStatus = false;
private void Parseanddownloadfiles()
{
//downloadhtml(mainurl);
if (bgw.CancellationPending == false)
{
/*backgroundWorker1.ReportProgress(0, "Parsing Links");
HtmlAgilityPack.HtmlWeb hw = new HtmlAgilityPack.HtmlWeb();
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc = hw.Load(path_exe + "\\page.html");
foreach (HtmlAgilityPack.HtmlNode link in doc.DocumentNode.SelectNodes("//a[#href]"))
{
string hrefValue = link.GetAttributeValue("href", string.Empty);
if (hrefValue.Contains("US"))
{
string url = "http://www.usgodae.org/ftp/outgoing/fnmoc/models/navgem_0.5/latest_data/" + hrefValue;
parsedlinks.Add(url);
if (bgw.CancellationPending == true)
return;
}
}*/
parsedlinks = urls;
countfiletodownload = parsedlinks.Count;
total = parsedlinks.Count;
backgroundWorker1.ReportProgress(0, "Downloading Files");
processStatus = true;
for (int i = 0; i < parsedlinks.Count && bgw.CancellationPending == false; i++)
{
try
{
using (WebClient client = new WebClient())
{
sw.Start();
Uri uri = new Uri(parsedlinks[i]);
string filename = "RadarImage" + i.ToString() + ".gif";//parsedlinks[i].Substring(71);
client.DownloadFileAsync(uri, filesdirectory + "\\" + filename);
Counter += 1;
percentage = Counter * 100 / total;
string filenametoreport = filename.Substring(1);
countfiletodownload--;
backgroundWorker1.ReportProgress(percentage, filenametoreport);//countfiletodownload, filenametoreport);
}
}
catch (Exception err)
{
string error = err.ToString();
}
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
BackgroundWorker bgw;
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
bgw = (BackgroundWorker)sender;
if (bgw.CancellationPending == true)
{
return;
}
else
{
Parseanddownloadfiles();
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (e.UserState.ToString() == "Downloading Main Url")
{
label3.Text = e.UserState.ToString();
}
if (e.UserState.ToString() == "Parsing Links")
{
label3.Text = e.UserState.ToString();
}
if (e.UserState.ToString() == "Downloading Files")
{
label7.Text = countfiletodownload.ToString();//parsedlinks.Count.ToString();
label3.Text = e.UserState.ToString();
}
if (processStatus == true)
{
if (e.UserState.ToString() != "Downloading Files")
{
label4.Text = e.UserState.ToString();
label7.Text = countfiletodownload.ToString();
progressBar1.Value = e.ProgressPercentage;
/*using (var bitmap = new Bitmap(this.Width, this.Height))
{
this.DrawToBitmap(bitmap, new Rectangle(0, 0, bitmap.Width, bitmap.Height));
bitmap.Save(#"e:\screens\ss.gif" + countscreenshots, System.Drawing.Imaging.ImageFormat.Gif);
countscreenshots += 1;
}*/
}
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
}
else
{
label3.Text = "Download Completed";
stopwatch.Reset();
stopwatch.Stop();
timer1.Stop();
}
if(e.Cancelled)
label3.Text = "Operation Cancelled";
button1.Enabled = true;
}
private void button2_Click(object sender, EventArgs e)
{
label3.Text = "Cancelling Operation";
backgroundWorker1.CancelAsync();
button2.Enabled = false;
timer1.Stop();
stopwatch.Stop();
stopwatch.Reset();
}
private void button1_Click(object sender, EventArgs e)
{
label3.Text = "";
label4.Text = "";
label7.Text = "";
backgroundWorker1.RunWorkerAsync();
timer1.Start();
stopwatch.Start();
button1.Enabled = false;
button2.Enabled = true;
}
private void button3_Click(object sender, EventArgs e)
{
Process.Start(filesdirectory);
}
private void timer1_Tick(object sender, EventArgs e)
{
label5.Text = string.Format("{0:hh\\:mm\\:ss}", stopwatch.Elapsed);
}
}
}
First time it's downloading fine but next time when clicking again the start button(button1) it's showing exception: System.Reflection.TargetInvocationException: 'Exception has been thrown by the target of an invocation.'
I tried to reset the progressBar value to 0 in the start button(button1) click event but it didn't solve the problem.
ArgumentOutOfRangeException: Value of '111' is not valid for 'Value'. 'Value' should be between 'minimum' and 'maximum'.
Parameter name: Value
The ArgumentOutOfRange exception is because you never reset Counter:
You define Counter as class level variable and initialize to 0:
int Counter = 0;
Then in your loop you call:
Counter += 1;
percentage = Counter * 100 / total;
When you click the button to restart the download, Counter still holds the final value of the previous run.
In button1_Click, prior to calling RunWorkerAsync
You need to reset it:
Counter = 0;
private void downloadFile(IEnumerable<string> urls)
{
foreach (var url in urls)
{
_downloadUrls.Enqueue(url);
}
// Starts the download
btnStart.Text = "Downloading...";
btnStart.Enabled = false;
pBarFileProgress.Visible = true;
label2.Visible = true;
label3.Visible = true;
label4.Visible = true;
label7.Visible = true;
DownloadFile();
}
private void DownloadFile()
{
if (_downloadUrls.Any())
{
WebClient client = new WebClient();
client.DownloadProgressChanged += client_DownloadProgressChanged;
client.DownloadFileCompleted += client_DownloadFileCompleted;
url = _downloadUrls.Dequeue();
if (url.Contains("animated") && url.Contains("infra"))
{
string startTag = "animated/";
string endTag = "/infra";
int index = url.IndexOf(startTag);
int index1 = url.IndexOf(endTag);
fname = url.Substring(index + 9, index1 - index - 9);
var countryName = codeToFullNameMap[fname];
downloadDirectory = tbxMainDownloadPath.Text;
downloadDirectory = Path.Combine(downloadDirectory, countryName);
}
else
{
fname = "Tempfile";
downloadDirectory = tbxMainDownloadPath.Text;
}
client.DownloadFileAsync(new Uri(url), downloadDirectory + "\\" + fname + ".gif");
lastDownloadedFile = downloadDirectory + "\\" + fname + ".gif";
label4.Text = downloadDirectory + "\\" + fname + ".gif";
return;
}
// End of the download
label2.Text = "All files have been downloaded";
}
private void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.Error != null)
{
// handle error scenario
throw e.Error;
}
if (e.Cancelled)
{
// handle cancelled scenario
}
if (url.Contains("animated") && url.Contains("infra"))
{
Image img = new Bitmap(lastDownloadedFile);
Image[] frames = GetFramesFromAnimatedGIF(img);
foreach (Image image in frames)
{
countFrames++;
image.Save(downloadDirectory + "\\" + fname + ".gif");
}
}
label2.Text = "Download Complete";
tracker.NewFile();
DownloadFile();
}
void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
tracker.SetProgress(e.BytesReceived, e.TotalBytesToReceive);
pBarFileProgress.Value = (int)(tracker.GetProgress() * 100.0);
label3.Text = e.BytesReceived + "/" + e.TotalBytesToReceive;
label7.Text = tracker.GetBytesPerSecondString();
label2.Text = "Downloading";
}
The start download button
private void btnStart_Click(object sender, EventArgs e)
{
downloadFile(lines);
}
Now I'm changing the labels visible property to true when I click the download button. But then the I see labels for some seconds before it's getting to the progressChanged event and update the labels.
The question is where should I change the visible to true of this labels 2,3,4,7 and that it will change it once to true ?
If you're concerned about showing the labels before you actually set any text to them, you should just make sure to set text to them before you get the progress changed event - e.g.
label3.Text = "0/calculating...";
label7.Text = "0 kbps";
label2.Text = "Preparing for download...";
in your downloadFiles method (before or after setting .Visible to true). On another note - pick better names for your labels! label3 might be better as something like lblTotalDownloaded, or label7 as lblDownloadSpeed, etc.
I have a button that start the backgroundworker:
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
button1.Enabled = false;
button2.Enabled = true;
}
A button to cancel the backgroundworker:
private void button2_Click(object sender, EventArgs e)
{
backgroundWorker1.CancelAsync();
button1.Enabled = true;
button2.Enabled = false;
}
The backgroundworker dowork.progresschanged.completed events:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker bgw = (BackgroundWorker)sender;
if (bgw.CancellationPending == true)
{
return;
}
else
{
Parseanddownloadfiles();
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
lblStatus.Text = "Downloading Filename: " + e.UserState.ToString();
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
stopwatch.Stop();
}
And last the method Parseanddownloadfiles()
private void Parseanddownloadfiles()
{
using (WebClient client = new WebClient())
{
client.DownloadFile(mainurl, path_exe + "\\page.html");
}
HtmlAgilityPack.HtmlWeb hw = new HtmlAgilityPack.HtmlWeb();
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc = hw.Load(path_exe + "\\page.html");
foreach (HtmlAgilityPack.HtmlNode link in doc.DocumentNode.SelectNodes("//a[#href]"))
{
string hrefValue = link.GetAttributeValue("href", string.Empty);
if (hrefValue.Contains("US"))
{
string url = "http://www.testing.com" + hrefValue;
parsedlinks.Add(url);
}
}
for (int i = 0; i < parsedlinks.Count; i++)
{
try
{
using (WebClient client = new WebClient())
{
string filename = parsedlinks[i].Substring(71);
client.DownloadFile(parsedlinks[i], filesdirectory + "\\" + filename);
backgroundWorker1.ReportProgress(0, filename);
}
}
catch (Exception err)
{
string error = err.ToString();
}
}
}
The important thing now is to make the cancel to work and then if it's possible to make the pause/continue after it.
Change your method int order to check the condition inside the loops into :
private void Parseanddownloadfiles()
{
using (WebClient client = new WebClient())
{
client.DownloadFile(mainurl, path_exe + "\\page.html");
}
HtmlAgilityPack.HtmlWeb hw = new HtmlAgilityPack.HtmlWeb();
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc = hw.Load(path_exe + "\\page.html");
foreach (HtmlAgilityPack.HtmlNode link in doc.DocumentNode.SelectNodes("//a[#href]"))
{
string hrefValue = link.GetAttributeValue("href", string.Empty);
if (hrefValue.Contains("US"))
{
string url = "http://www.testing.com" + hrefValue;
parsedlinks.Add(url);
}
if (bgw.CancellationPending == true)
return;
}
for (int i = 0; i < parsedlinks.Count && bgw.CancellationPending == false; i++)
{
try
{
using (WebClient client = new WebClient())
{
string filename = parsedlinks[i].Substring(71);
client.DownloadFile(parsedlinks[i], filesdirectory + "\\" + filename);
backgroundWorker1.ReportProgress(0, filename);
}
}
catch (Exception err)
{
string error = err.ToString();
}
}
If you need to cancel the downloads, my favorite solution would be to use some Tasks and a CancellationTokenSource.
Regards
I'm trying to fill my ProgressBar inside a while loop.
But somehow the Progressbar value wont grow.
I want the code to open a textfile and to post a request for each row in it.
My code for this:
public void registerAccounts()
{
const Int32 BufferSize = 128;
using (var fileStream = File.OpenRead(nsTextBox3.Text))
using (var streamReader = new StreamReader(fileStream, Encoding.UTF8, true, BufferSize))
{
String line;
while ((line = streamReader.ReadLine()) != null)
{
var request = (HttpWebRequest)WebRequest.Create("http://registration.zwinky.com/registration/register.jhtml");
var postData = "form=reg&success=http://profile.zwinky.com/zwinkyprofile/main.jhtml?username=&tp=&user.partnerId=ZZzer000&source=zwinky&design=classic&ad=/&user.userName=" + line + "&user.password=" + nsTextBox1.Text + "&user.passwordConfirm=" + nsTextBox1.Text + "&user.secretQId=1&user.secretQAnswer=" + line + "&user.birthdayMonth=1&user.birthdayDay=1&user.birthdayYear=1996&user.gender=M&user.emailAddr=" + nsTextBox2.Text + "&emailAddrConfirm=" + nsTextBox2.Text + "&x=42&y=51&partnerCode=/";
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
}
}
}
How would I let the ProgressBar in my GUI grow now?
I thought about counting the lines inside the text document like this:
var lineCount = File.ReadLines(nsTextBox3.Text).Count();
and then run a for loop in it. But it wont grow sadly.
Would appreciate any kind of help.
You appear to be running this method on the UI thread of your application. This thread is responsible for updating the UI, so while it's busy with the loop it can't do that. What likely happens is that once your loop completes the progress bar is updated straight to 100% and you don't see it.
Look at using a Background Worker.
It takes care of the above concerns by doing all of the threading and callbacks for you in a very simple manner.
Example taken straight from the MSDN article:
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
namespace SL_BackgroundWorker_CS
{
public partial class Page : UserControl
{
private BackgroundWorker bw = new BackgroundWorker();
public Page()
{
InitializeComponent();
bw.WorkerReportsProgress = true;
bw.WorkerSupportsCancellation = true;
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
}
private void buttonStart_Click(object sender, RoutedEventArgs e)
{
if (bw.IsBusy != true)
{
bw.RunWorkerAsync();
}
}
private void buttonCancel_Click(object sender, RoutedEventArgs e)
{
if (bw.WorkerSupportsCancellation == true)
{
bw.CancelAsync();
}
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
for (int i = 1; (i <= 10); i++)
{
if ((worker.CancellationPending == true))
{
e.Cancel = true;
break;
}
else
{
// Perform a time consuming operation and report progress.
System.Threading.Thread.Sleep(500);
worker.ReportProgress((i * 10));
}
}
}
private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if ((e.Cancelled == true))
{
this.tbProgress.Text = "Canceled!";
}
else if (!(e.Error == null))
{
this.tbProgress.Text = ("Error: " + e.Error.Message);
}
else
{
this.tbProgress.Text = "Done!";
}
}
private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.tbProgress.Text = (e.ProgressPercentage.ToString() + "%");
}
}
}
Put your loop in DoWork and your progress bar in ProgressChanged. Simples!
you can try this,this is not perfect but worked
int linecount=0;
while ((line = streamReader.ReadLine()) != null)
{
linecount=linecount+1;
}
int number=0;
while ((line = streamReader.ReadLine()) != null)
{
number=number+1;
// what is yor work
progressBar1.Value = i * progressBar1.Maximum / linecount; //show process bar counts
LabelTotal.Text = i.ToString() + " of " + linecount; //show number of count in lable
int presentage = (i * 100) / linecount;
LabelPresentage.Text = presentage.ToString() + " %"; //show precentage in lable
Application.DoEvents(); //keep form active in every loop
}
I have a program that gets the app name, place them on a listbox and sends them to the other window if you click the send button.
What I wanted to know is, is it possible for it to automatically send every 10 seconds after a single click on the send button? If yes, how can I possibly do that?
There's the codes, in case if it brings of any help.
private void cmd_send_Click_1(object sender, EventArgs e)
{
String processID = "";
String processName = "";
String processFileName = "";
String processPath = "";
string hostName = System.Net.Dns.GetHostName();
listBox1.BeginUpdate();
try
{
for (int i = 0; i < listBox1.Items.Count; i++)
{
piis = GetAllProcessInfos();
try
{
// String pno = textBox4.Text.ToString();
// String path = textBox5.Text.ToString();
// String name = textBox6.Text.ToString();
// String user = textBox7.Text.ToString();
// output.Text += "\n Sent data : " + pno + " " + user + " " + name + " " + path ;
processID = piis[i].Id.ToString();
processName = piis[i].Name.ToString();
processFileName = piis[i].FileName.ToString();
processPath = piis[i].Path.ToString();
output.Text += "\n\nSENT DATA : \n\t" + processID + "\n\t" + processName + "\n\t" + processFileName + "\n\t" + processPath + "\n";
}
catch (Exception ex)
{
wait.Abort();
output.Text += "Error..... " + ex.StackTrace;
}
NetworkStream ns = tcpclnt.GetStream();
String data = "";
//data = "--++" + " " + textBox4.Text + " " + textBox5.Text + " " + textBox6.Text + " " + textBox7.Text;
data = "--++" + " " + processID + " " + processPath + " " + processFileName + " " + hostName;
if (ns.CanWrite)
{
byte[] bf = new ASCIIEncoding().GetBytes(data);
ns.Write(bf, 0, bf.Length);
ns.Flush();
}
}
}
finally
{
listBox1.EndUpdate();
}
}
Any help would be greatly appreciated.
You could place your code inside a single method, call that method initially on button click and start/stop your timer depending on it's current state.
private Timer _timer;
public Form() // Initialize timer in your form constructor
{
InitializeComponent();
_timer = new Timer();
_timer.Interval = 10000; // miliseconds
_timer.Tick += _timer_Tick; // Subscribe timer to it's tick event
}
private void _timer_Tick(object sender, EventArgs e)
{
SendData();
}
private void cmd_send_Click_1(object sender, EventArgs e)
{
if (!_timer.Enabled) // If timer is not running send data and start refresh interval
{
SendData();
_timer.Enabled = true;
}
else // Stop timer to prevent further refreshing
{
_timer.Enabled = false;
}
}
private void SendData()
{
// Your code here
}
EDIT:
If you're using .NET framework 4.5 or above you can do the same thing in using async/await.
private bool keepRefreshing;
private async void cmd_send_Click_1(object sender, EventArgs e)
{
if (keepRefreshing)
{
keepRefreshing = false;
return;
}
keepRefreshing = true;
while (keepRefreshing)
{
// Your code here
await Task.Delay(10000);
}
}
On button click it will send data and it will keep sending with delay of 10 seconds. When you press the button second time it will stop refreshing interval, third time it will start again and so on..
// Declare a timer
Timer tmr = new Timer();
tmr.Interval = 10000; // 10 second
tmr.Tick += timerHandler; // We'll write it in a bit
tmr.Start(); // The countdown is launched!
private void timerHandler(object sender, EventArgs e) {
// Here the code what you need each 10 seconds
tmr.Stop(); // Manually stop timer, or let run indefinitely
}
Their are many ways one is follow.
private void cmd_send_Click_1(object sender, EventArgs e)
{
bool isResend=true;
while (isResend==true)
{
// Put all your here
System.Threading.Thread.Sleep(10000);
}
}
Other ways are using Timer, etc...
Everyone's answer is cool, but as for me if you really need that "click" as start, i'll do it this way.
Initiate events for timer & background worker inside form load.
set timer.start(); inside click.
Once ticking, if backgroundworker is not busy, execute background worker.
Ensure that you don't directly set label1.text = "send some works here." inside the background worker, it will cause error.
Hope this helps.