Update variable on each loop [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 9 years ago.
wrote this code which calls Async function once on button click.
But i want it to run continuously updating the Page variable on every loop.
example: 1st loop page = 1 second loop page =2 so on.. and stop the loop on another button click.
private void button2_Click(object sender, EventArgs e)
{
var searchParameters = new PlayerSearchParameters
{
Page = 2,
League = League.BarclaysPremierLeague,
Nation = Nation.England,
Position = Position.CentralForward,
Team = Team.ManchesterUnited
};
LoginM.SearchItemsAsync(searchParameters);
}
Sorry for not giving a detailed explanation/
The searchParamters are obtained from textboxes and sent to a Async function on LoginM.cs file by calling :
LoginM.SearchItemsAsync(searchParameters);
I want LoginM.SearchItemsAsync(searchParameters); to be called continuously and each time it gets called the "Page" variable should be incremented by +1
How do i create a loop to do the above ?
Its a WinForm Project.

You'll need a place to hold your current value, in the example I've made it to be a local named pageNum. Inside your loop then, you'll increment that variable and assign it to the Page property on the PlayerSearchParameters object being constructed in its initializer.
If you want the method to wait for the async method to be completed before starting the next iteration of the loop, make the event handler async and await the result of the one you're calling.
private async void button2_Click(object sender, EventArgs e)
{
var pageNum = 0;
while(true) //<-- Insert whatever your real condition is here instead of true
{
var searchParameters = new PlayerSearchParameters
{
Page = ++pageNum,
League = League.BarclaysPremierLeague,
Nation = Nation.England,
Position = Position.CentralForward,
Team = Team.ManchesterUnited
};
await LoginM.SearchItemsAsync(searchParameters);
}
}
If you're trying to get this behavior without having to click a button first, you could put the body of the method in a handler for the Load event on your form instead.

Related

Using ProgressBar for specific 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 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);
}

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# Windows Forms - outputting info to a textbox without crashing [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 11 years ago.
In a Windows Forms app, I am using Quartz.NET to run some tasks every few minutes. Previously, this application was a console application that was invoked based on a schedule but for various reasons this wasn't ideal - back then all debug info was outputted to the console.
In this version, I need a way to show the debug information for a job on the user's screen. My initial idea was a new form that is shown when a job is run, and all debug information is appended to a multiline textbox on that form. However, this doesn't work as most of the app seems to crash when I do this.
Any other ideas?
EDIT: Sorry for any confusion. This is what's called when a job executes:
public virtual void Execute(JobExecutionContext context)
{
RunJob jobForm = new RunJob();
jobForm.Show();
jobForm.JobLabel = context.JobDetail.JobDataMap.GetString("Name");
for (int i = 0; i < 100; i++)
{
jobForm.WriteLine(i.ToString());
}
jobForm.Hide();
}
And this is the contents of the 'RunJob' form:
public partial class RunJob : Form
{
public string JobLabel
{
get
{
return lblJobName.Text;
}
set
{
lblJobName.Text = value;
}
}
public void WriteLine(string text)
{
textBox1.AppendText(text + Environment.NewLine);
}
public RunJob()
{
InitializeComponent();
}
}
Basically, the RunJob window freezes when the text is being appended, when ideally it'd just add the text smoothly. I understand 'crash' was a very poor choice of word! My excuse is that it's early in the morning, ahem
i dont see anything wrong in above code that could lead it to deadlock or whatever it is, except this line: jobForm.JobLabel = context.JobDetail.JobDataMap.GetString("Name");
what does this line does, there must be something wrong in this line,
try putting some hard coded string instead of context.JobDetail.JobDataMap.GetString("Name"); and tell me if it still doesn't work.
Job and UI form should obviously be at separate threads. Job thread should write to the form and then close it when unneeded.
Presuming you have an Action action that is invoked on UI thread:
public virtual void Execute(JobExecutionContext context)
{
RunJob jobForm;
var name = context.JobDetail.JobDataMap.GetString("Name");
action(()=> { jobForm = new RunJob(); jobForm.Show(); jobForm.JobLabel = name;});
for (int i = 0; i < 100; i++)
{
var txt = i.ToString();
action(()=>{ jobForm.WriteLine(txt); });
}
action(()=> { jobForm.Hide(); });
}

how to make best player screen? [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 11 years ago.
i am using visual studio 2008 c# winform. . i've make sudoku game which is working well . . i want to make best player screen for it and score depend on how much time the player take to complete game . .
i am using another form to take player name when he meets the condition for best player and give the name to label on main form but its not working.here is my code:
private void button1_Click(object sender, EventArgs e)
{
Form1 main = new Form1();
main.lbBEN.Text = textBox1.Text;
this.Close();
}
and this on another form:
if (emint<bmint)
{
best b = new best();
b.ShowDialog();
}
please guide me. . .THANK you
Add a public property to the second form and just below the ShowDialog(), sets the form1 label.Text to that property containing the name of the user.
public partial class Form2 : Form
{
string _highestScoreUser = string.Empty;
public Form2()
{
}
public string HighestScoreUser
{
get{ return _highestScoreUser; }
set{ _highestScoreUser = value; }
}
}
In Form1 code after ShowDialog is called like
{
Form2 form = new Form2();
form.ShowDialog();
form1.label.Text = form.HighestScoreUser;
}
Hope this help
You've created a brand new Form1 object unrelated to the Form1 that is already on the screen. You need to somehow pass a reference to the real Form1 the the secondary form.

Categories