Using ProgressBar for specific time [closed] - c#

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I want my ProgressBar starting in some point in my code and run total of seconds until my file finish, and of course I know how long the run of my file will take.
I try to read on MSDN but I did not understood how to use it.
My application run files (wireshark file, send the packet using bittwist) and each file will run few seconds and I want the option to see the progress ongoing.
For example I want to set my ProgressBar running for 30 seconds.
How can I do it?

Maybe you want something like this:
public void AnimateProgBar (int milliSeconds)
{
if (!timer1.Enabled) {
progressBar1.Value = 0;
timer1.Interval = milliSeconds / 100;
timer1.Enabled = true;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (progressBar1.Value < 100) {
progressBar1.Value += 1;
progressBar1.Refresh();
} else {
timer1.Enabled = false;
}
}
Then you just have to call AnimateProgBar(2000) to have your ProgressBar animated during 2 seconds.
EDIT: Sorry, I posted code in VB.NET. Modified to C#.
EDIT: You can add the handler and call the function in this way (for example):
private void Form1_Load(object sender, EventArgs e)
{
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
AnimateProgBar(2000);
}

Related

WPF, why my BackgroundWorker function only runs one time? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I have a function that i want to run it every 1 second and beside that i do have other stuff ,
because im using Thread on my other function and avoiding Window Crashes i decided to use Backgroundworker to call the function that suppose to run like this:
Main()
{
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.RunWorkerAsync();
}
public void worker_DoWork(object sender, EventArgs e)
{
AutoChecking(); // thats a function should Run on Background every 1 second
}
public void AutoChecking()
{
this.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
{
if (SystemisGood == true)
Updatecolor.Fill = Green;
else
Updatecolor.Fill = Red;
}));
}
However this function only works one time now any reason or solution to make it work every one second and Stay with backgroundworker ?!
P.S: i dont want to use Timer...
It is wasteful to not use a timer, since those are very lightweight and just send a periodic message, but you could accomplish what you want by using a low overhead polling loop and checking the time, much as what is done by the timer code itself. For example:
Main()
{
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.RunWorkerAsync();
}
bool exitBGThread = false;
public void worker_DoWork(object sender, EventArgs e)
{
TimeSpan interval = new TimeSpan(0, 0, 1);
while (!exitBGThread)
{
DateTime start = DateTime.Now;
AutoChecking(); // thats a function should Run on Background every 1 second
while (!exitBGThread)
{
DateTime cur = DateTime.Now;
if (cur - start >= interval)
break;
Thread.Sleep(100);
}
}
}
public void AutoChecking()
{
this.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
{
if (SystemisGood == true )
Updatecolor.Fill = Green;
else
Updatecolor.Fill = Red;
}));
}
This is a bit simplified as you would want to use lock { } if you actually used exitBGThread, but you get the idea.

How to move PictureBox with Thread? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I'm learning threads in C# so my first program will be 2 images that will be moving. But the problem is that I get an error when I try to do a new point in a thread:
Here's my code:
namespace TADP___11___EjercicioHilosDatos
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int x = 0;
int y = 0;
private void Form1_Load(object sender, EventArgs e)
{
Thread Proceso1 = new Thread(new ThreadStart(Hilo1));
Proceso1.Start();
}
public void Hilo1()
{
while (true)
{
x = pictureBox1.Location.X - 1;
y = pictureBox1.Location.Y;
pictureBox1.Location = new Point(x, y);
}
}
}
}
You can only update a control from the thread that control was created on. Controls do have an Invoke method that you can call from another thread. This method takes a delegate that specifies the work you would like to do on the control's thread:
var updateAction = new Action(() => { pictureBox1.Location = new Point(x,y); });
pictureBox1.Invoke(updateAction);
You have to Invoke it. For [obvious] reasons, you can't access controls created by a different thread so you have to use a delegate. Several similar SO questions:
How to update the GUI from another thread in C#? (111 upvotes)
Writing to a textBox using two threads
How to update textbox on GUI from another thread in C#
Writing to a TextBox from another thread?
If you check out the first link, Ian's great answer will demonstrate how you should do this in .Net 2.0 and 3.0. Or you can scroll down to the next answer, Marc's, which will show you how to do it in the simplest way.
Code:
//worker thread
Point newPoint = new Point(someX, someY);
this.Invoke((MethodInvoker)delegate {
pictureBox1.Location = newPoint;
// runs on UI thread
});

Knowing the status of a very long function (execution time) in another class [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Currently I have a background thread whose doWork calls a function similar to below.
private void ThreadForAnalyzingReqFile_DoWork(object sender, DoWorkEventArgs e)
{
AnotherClass.AVeryLongTimedFunction();
}
Now, the code shall wait until AVeryLongTimedFunction() in AnotherClass finishes (that may take about 1-2 minutes) While this happens, how do I know exactly what's happening? Is there any way I can be notified that function (in another class) finishes?
This thread is in my MainWindow class of WPF. I am using Visual Studio 2010.
There are many ways to do this. Two easy options:
(1) Create an event in your UI class such as UpdateProgress, and notify that event at meaningful intervals
Example:
private void ThreadForAnalyzingReqFile_DoWork(object sender, DoWorkEventArgs e)
{
AnotherClass processor = new AnotherClass();
processor.ProgressUpdate += new AnotherClass.ReallyLongProcessProgressHandler(this.Processor_ProgressUpdate);
processor.AVeryLongTimedFunction();
}
private void Processor_ProgressUpdate(double percentComplete)
{
this.progressBar1.Invoke(new Action(delegate()
{
this.progressBar1.Value = (int)(100d*percentComplete); // Do all the ui thread updates here
}));
}
And in "AnotherClass"
public partial class AnotherClass
{
public delegate void ReallyLongProcessProgressHandler(double percentComplete);
public event ReallyLongProcessProgressHandler ProgressUpdate;
private void UpdateProgress(double percent)
{
if (this.ProgressUpdate != null)
{
this.ProgressUpdate(percent);
}
}
public void AVeryLongTimedFunction()
{
//Do something AWESOME
List<Item> items = GetItemsToProcessFromSomewhere();
for (int i = 0; i < items.Count; i++)
{
if (i % 50)
{
this.UpdateProgress(((double)i) / ((double)items.Count)
}
//Process item
}
}
}
(2) Create a progress percentage field on AnotherClass. Occasionally interrogate this in your UI on a timer.
Try to pass a callback function to your "VeryLongTimedFunction" and call that every time some kind of "progress" event happens, like each time 50 items are processed, or 20 iterations are made , or whatever is the case with your operation.
As others hinted, there are multiple ways of achieving that, however the simplest seems to be just to use BackgroundWorker instead of a thread.
To indicate progress, simply set WorkerSupportsCancellation property to true and then invoke worker.ReportProgress(percentage complete) to indicate progress. For a completion notification use event notification, e.g.
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(method_run_on_complete);
private void method_run_on_complete(object sender, DoWorkEventArgs e) { ... }
For more details see:
http://www.dreamincode.net/forums/topic/112547-using-the-backgroundworker-in-c%23/
http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/28774446-144d-4716-bd1c-46f4bb26e016

C# integer variable in foreach loop [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
In C# I have a foreach loop where I want to ++ a integer.
The code is like this:
private void btnClick(object sender, EventArgs e)
{
int Counter = 0;
foreach (SettingsProperty currrentProperty in Properties.Settings.Default.Properties)
{
Counter++;
}
lblText.Text = Counter.ToString();
}
Simple, but of course because I have to assing the integer the variable sticks to 0, otherwise the compiler errors. So the lblText.Text prints 0 to me.
I just can't get it working properly..
Sure this is an easy one, but I couldn't find a awnser.
I think that Properties.Settings.Default.Properties is empty . So to get sure that it is empty try:
private void btnClick(object sender, EventArgs e)
{
if(Properties.Settings.Default.Properties.Count != 0)
{
int Counter = 0;
foreach (SettingsProperty currrentProperty in Properties.Settings.Default.Properties)
{
Counter++;
//Some stuff here else just use .Count without use a foreach
}
lblText.Text = Counter.ToString();
}
else
throw new Exception("Properties.Settings.Default.Properties is empty");
}
Else try to set some breakpoints before compile the code.

how to open usercontrol and close 2 seconds [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 12 years ago.
Hello People how can i open userControl and close in the 2 seconds and show another form?
c# WinForms
public void MyFunction()
{
firstForm.ShowDialog();
secondForm.Show();
}
public void firstForm_Load(object sender, EventArgs e)
{
Timer timer = new System.Windows.Forms.Timer() { Interval = 2000 };
timer.Tick += delegate { timer.Stop(); Close(); };
timer.Start();
}

Categories