In my XAML file, I create a ChartPlotter then I create in c# my LineGraphs and attatch them to my ChartPlotter. I tried to find a way to update these LineGraphs after their creation, but it always failed.
The only solution I found, is that I delete all LineGraphs , re-create them with new values and finally link them to my ChartPlotter.
How can I update LineGraph ?
for (int i = 0; i < lgs.Length; i++)
if (lgs[i] != null)
lgs[i].RemoveFromPlotter();
PS : lgs is my LineGraph array.
To update your LineGraphs, you have to use the ObservableDataSource object instead of the CompositeDataSource. With this object, you can use the method AppendAsync().
public partial class MainWindow : Window
{
public ObservableDataSource<Point> source1 = null;
public MainWindow()
{
InitializeComponent();
this.Loaded += MainWindow_Loaded;
}
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
// Create source
source1 = new ObservableDataSource<Point>();
// Set identity mapping of point in collection to point on plot
source1.SetXYMapping(p => p);
// Add the graph. Colors are not specified and chosen random
plotter.AddLineGraph(source1, 2, "Data row");
// Force everyting to fit in view
plotter.Viewport.FitToView();
// Start computation process in second thread
Thread simThread = new Thread(new ThreadStart(Simulation));
simThread.IsBackground = true;
simThread.Start();
}
private void Simulation()
{
int i = 0;
while (true)
{
Point p1 = new Point(i * i, i);
source1.AppendAsync(Dispatcher, p1);
i++;
Thread.Sleep(1000);
}
}
}
All you want is in the while of the method Simulation.
source1.AppendAsync(Dispatcher, p1);
Related
I don't know how to implement a method with a separate thread using the BackgroundWorker in WinForms.
I want this method (after every click on a button) to perform:
create ProgressBar (each new one under the previous one)
create Bitmap and BackgroundWorker
set color of every pixel in that Bitmap in the separate thread using BackgroundWorker
display a precentage progress on the ProgressBar
after completing: create a new form with bitmap on the background
after completing: remove the ProgressBar
My code:
List<BackgroundWorker> Workers;
List<ProgressBar> Progress;
int OperationsCount = 0;
private void ShowProgress(int n, int percent)
{
Progress[n].Value = percent;
}
private void Blend(object sender, DoWorkEventArgs e)
{
Bitmap BlendedImage = ... // creates a bitmap
for (int i = 0; i < BlendedImage.Width; i++)
{
for (int j = 0; j < BlendedImage.Height; j++)
{
... //changing colour of every pixel
}
this.Invoke(new Action(()=>ShowProgress((int)e.Argument, (int)(100 * (double)(i/BlendedImage.Width)))));
}
Form BlendedImage_Form = new Form();
BlendedImage_Form.Size = new Size(BlendedImage.Width, BlendedImage.Height);
BlendedImage_Form.BackgroundImage = BlendedImage;
BlendedImage_Form.BackgroundImageLayout = ImageLayout.Stretch;
this.Invoke(new Action(() => BlendedImage_Form.Show()));
}
private void PerformBlending_Button_Click(object sender, EventArgs e)
{
int n = OperationsCount++;
Progress.Add(new ProgressBar());
Progress[n].Size = ...
Progress[n].Location = ...
Progress[n].Maximum = 100;
this.Controls.Add(Progress[n]);
Workers.Add(new BackgroundWorker());
Workers[n].DoWork += new DoWorkEventHandler(Blend);
Workers[n].RunWorkerCompleted += (object _sender, RunWorkerCompletedEventArgs _e) =>
{
//OperationsCount--;
//Progress[n].Dispose();
//this.Controls.Remove(Progress[n]);
//Progress.RemoveAt(n);
};
Workers[n].RunWorkerAsync(n);
}
When I click the button only once then everything seems to be good but when I click the button two times then program:
creates the first ProgressBar which shows progress correctly and the new form and bitmap are displayed also correctly
creates the second ProgressBar but it doesn't show the progress at all and no form and no bitmap is displayed.
PS I'd rather use BackgroundWorker than other tools.
As per your comment here is the solution
public void DoSomething()
{
if (this.InvokeRequired)
{
this.Invoke(new Action(()=> DoSomething()));
}
else
{
// update the ui from here, no worries
}
}
In this code, I am modifying the object on main thread. If the calls made from non-UI thread this will goes in InvokeRequired.
// From this code you given in comment
https://pastebin.com/45jQXCt9
Please try with making instance inside invoke. It should work.
// PaddlerList (Form 1)
public void RefreshListView()
{
PaddlerListView.Items.Clear();
PaddlerToList();
PaddlerListView.Refresh();
Console.WriteLine("Refresh....");
}
public void PaddlerToList() // Just adds
{
for (int i = 1; i < Main.paddlerList.Count(); i++) // Repeats for all
{
string[] array = new string[4];
ListViewItem item;
array[0] = Main.paddlerList[i].FirstName.ToString();
array[1] = Main.paddlerList[i].LastName.ToString();
array[2] = Main.paddlerList[i].Weight.ToString();
array[3] = Main.paddlerList[i].PreferredSide.ToString();
item = new ListViewItem(array);
PaddlerListView.Items.Add(item);
}
}
private void RefreshList_button_Click(object sender, EventArgs e)
{
RefreshListView();
}
// NewPaddler (Form 2)
private void SubmitPaddler_button_Click(object sender, EventArgs e)
{
// Code here
PaddlerList ListViewRefresh = new PaddlerList(); // Creates an instant of the other form, so it can run the procedure
ListViewRefresh.RefreshListView();
}
When a new paddler is added (the submit button is pressed), the console outputs "Refresh...." showing that the function has been run, but the ListView doesn't refresh
However, when I set a button on the same form as the ListView, it does refresh the ListView with the new items, when the button is pressed.
I can't work out what the issue is here? I think it's something to do with protection levels of the ListView.
Thanks!
When a new PaddlerList object is created, all member variables, like in your case, Items, recieve a fresh start. I think you need to pass the original PaddlerList to your second form in order to actualize the correct form.
I found a solution:
New Paddler Form
// NewPaddler Form
PaddlerList ListObject_global = null;
public NewPaddler(PaddlerList PaddlerList_Object)
{
InitializeComponent();
FormBorderStyle = FormBorderStyle.FixedDialog;
ListObject_global = PaddlerList_Object;
}
if (ListObject_global != null)
{
ListObject_global.RefreshListView(); // Runs function in PaddlerList
}
Paddler List Form
// PaddlerList Form
public void RefreshListView()
{
PaddlerToList();
PaddlerListView.Refresh();
Console.WriteLine("Refresh....");
}
I'm separating out logic from one class to another in my Windows Form application. When all in one class, it works fine but I am moving the logic to it's own respective classes now. Having some issues getting at the backgroundWorker from a different class.
I have in class A
public partial class ClassA : Form
BackgroundWorker essentialBgWorker = new BackgroundWorker();
public ClassA()
{
InitializeComponent();
//essentialBgWorker
essentialBgWorker.DoWork += new DoWorkEventHandler(essentialBgWorker_DoWork);
essentialBgWorker.ProgressChanged += new ProgressChangedEventHandler(essentialBgWorker_ProgressChanged);
essentialBgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(essentialBgWorker_RunWorkerCompleted);
essentialBgWorker.WorkerReportsProgress = true;
}
That is a form that has a button which when clicked, copies files to another directory.
private void copyButton_Click(object sender, EventArgs e)
{
clickedButton = ((Button)sender).Name.ToString();
itemsChanged = ((Button)sender).Text.ToString();
essentialBgWorker.RunWorkerAsync();
}
This runs the background worker:
public void essentialBgWorker_DoWork(object sender, DoWorkEventArgs e)
{
string buttonSender = clickedButton; //copyButton, deleteButton, etc.
switch (buttonSender)
{
case "copyButton":
//this is pseudocode - the important part being that this is where I would call the method from the other class
ClassB.copyDocuments();
break;
case "deleteButton":
//this is pseudocode - the important part being that this is where I would call the method from the other class
ClassB.deleteDocuments();
break;
default:
essentialBgWorker.CancelAsync();
break;
}
}
In my other class (ClassB) for this example I have the method that is called when the button is clicked (should be handling the logic).
public void copyDocuments()
{
ClassA classA = new ClassA();
//
//the logic that handles copying the files
//gets the filecount!
//Report to the background worker
int totalFileCount = fileCount;
int total = totalFileCount; //total things being transferred
for (int i = 0; i <= total; i++) //report those numbers
{
System.Threading.Thread.Sleep(100);
int percents = (i * 100) / total;
classA.essentialBgWorker.ReportProgress(percents, i);
//2 arguments:
//1. procenteges (from 0 t0 100) - i do a calcumation
//2. some current value!
}
//Do the copying here
}
I keep having an issue with this line:
classA.essentialBgWorker.ReportProgress(percents, i);
This line worked when it was in ClassA - but once bringing it into ClassB gives an error:
ClassA.essentialBgWorker' is inaccessible due to it's protection level
Just looking for some assistance on the proper way to get it to fire from the other class.
You must add public modifier to essentialBgWorker
public BackgroundWorker essentialBgWorker = new BackgroundWorker();
I was trying to update status on UI for a Long Running Operating. I've created a demo form based application, task it have multiple rows, each row is having days and default values in each column of datagrid is 0, once computation file computes one iteration for one day it will update UI and set 1 for that day.
I am using threading, delegates and events to implement this and it is working as expected if I put Thread.Sleep(100) between two event calls. If I put "Thread.Sleep(100)" inside last nested for loop then it updates UI as expected but as soon as I remove it and run loop without sleep, then it skips some of the columns on UI and directly update last few/random columns, as you can see in attached image link(Image of output of my code without thread sleep) only last column is getting updated.
If I am not mistaken all the events are getting fired in sequence then they should update UI in sequence too but it's not happening and I don't know why. I don't want to do this Sleep thing because I have around 14 calls in actual application for UI status update and it will run under a loop so if It put sleep(100) then it will cost me a lot, is there any way to do it without SLEEP?
Image of output of my code without thread sleep
public class Class1 : IGenerate
{
public event MessageEventHandler OnMessageSending;
public void LongOperationMethod(BindingList<Status> _statusData)
{
if (OnMessageSending != null)
{
MessageEventArgs me = new MessageEventArgs();
/// Loop for 2-3 Weeks
for (; ; ){
/// Loop for 7 day
for (; ; )
{
/// Calculation on everyday
for (int j = 0; j != 1000; ++j)
{
// to do
}
me.weekNo = k;
me.DayNo = i;
OnMessageSending(me);
}
}
me.Message = "Process completed successfully...";
OnMessageSending(me);
}
else
{
throw new ArgumentException("Event hasn`t been rised, so we cannot continue working.");
}
}
}
**UI file:**
<pre><code>
public partial class Form1 : Form
{
BindingList<Status> _statusData = new BindingList<Status>();
delegate void StringParameterDelegate(string value);
Class1 cls = new Class1();
public Form1()
{
InitializeComponent();
labelProgress.Text = "";
}
private void button1_Click_1(object sender, EventArgs e)
{
for (int i = 1; i <= 2; ++i)
{
_statusData.Add(new Status { Week = "Week" + i, Day1 = 0, Day2 = 0, Day3 = 0, Day4 = 0, Day5 = 0, Day6 = 0, Day7 = 0 });
}
dataGridView1.DataSource = _statusData;
}
private void button2_Click(object sender, EventArgs e)
{
Thread t1 = new Thread(() => StartingThread(_statusData));
t1.Start();
}
void StartingThread(BindingList<Status> _statusData)
{
IGenerate generate = new Class1();
generate.OnMessageSending += new MessageEventHandler(generate_OnMessageSending);
generate.LongOperationMethod(_statusData);
}
private void generate_OnMessageSending(MessageEventArgs e)
{
int weekNo = e.weekNo;
int dayNo = e.DayNo;
this.dataGridView1.BeginInvoke(new MethodInvoker(() => dataGridView1.Rows[e.weekNo].Cells[e.DayNo + 1].Value = 1));
this.labelProgress.BeginInvoke(new MethodInvoker(() => this.labelProgress.Text = e.Message));
}
}
</code></pre>
It looks like you are sending the same instance of MessageEventArgs every time, and just updating that one instance on the background thread. This means that your event handler on the UI thread will retrieve the exact same instance of MessageEventArgs that is being updated in the loop! By the time your UI handler gets the MessageEventArgs, its .weekNo and .DayNo properties could well have been modified by the next iteration of the loop, since they are running on separate threads.
To fix this, create a new instance of MessageEventArgs every time you call OnMessageSending().
Relevant snippet:
MessageEventArgs me = new MessageEventArgs();
me.weekNo = k;
me.DayNo = i;
OnMessageSending(me);
So I'm trying to change the text from a WinForms project, from another class than the Form class.
It should work like this:
But instead it does this:
The way I used to do it is pass along the object as a parameter to my other class and from that other class I could change the text. I do the same with the progressbar and it does work there, so it's weird that it works with the progressbar but not the label.
I use this method to change the progressbar:
public void IncreaseProgress(int progBarStepSize, String statusMsg, int currentProject=-1) {
if (currentProject != -1) {
lblStatus.Text = String.Format("Status: {0} | project {1} of {2}",statusMsg,currentProject,ProjectCount);
}
else {
lblStatus.Text = String.Format("Status: {0}",statusMsg);
}
pb.Increment(progBarStepSize);
}
And here is where I use the method:
public void InitialiseFile(List<string> filePaths, int eurojobType)
{
foreach (string sheet in outputSheets) {
switch (sheet) {
case "Summary":
for (int i = 0; i < filePaths.Count; i++) {
var filePath = filePaths[i];
IncreaseProgress(1, "Reading Summary", i);
worksheetIn = excelReader.ReadExcelSummary(filePath);
IncreaseProgress(1, "Writing Summary", i);
excelWriter.WriteExcelSummary(worksheetIn);
}
break;
case "Monthly_Cat1":
for (int i = 0; i < filePaths.Count; i++) {
var filePath = filePaths[i];
IncreaseProgress(1, "Reading Monthly", i);
worksheetIn = excelReader.ReadExcelMonthly(filePath);
IncreaseProgress(1, "Writing Monthly", i);
excelWriter.WriteExcelMonthly(worksheetIn);
}
break;
}
}
IncreaseProgress(1, "Completed!");
}
Now I know this code works because the progressbar increments. And it should jump in the first if-loop because i gets passed as a parameter, which is never -1.
//manager class
private Label lblStatus;
private ProgressBar pb;
public Manager(ProgressBar pb, Label lbl){
this.pb = pb;
lblStatus = lbl;
}
//Form class
Manager mgr = new Manager(progressBar1, lblStatus, projectFilePaths.Count, outputSheets.ToArray(), exportPath);
mgr.InitialiseFile(projectFilePaths, eurjobType);
You can call lblStatus.Refresh(); to force the control to be redrawn, after setting its Text.
But consider Slaks comment:
Don't do blocking work on the UI thread
You can consider using BackgroundWorker or Task.Run or async/await pattern instead.
As an example:
private async void button1_Click(object sender, EventArgs e)
{
await Task.Run(() =>
{
for (int i = 0; i < 10000; i++)
{
this.Invoke(new Action(() =>
{
label1.Text = i.ToString();
label1.Refresh();
}));
}
});
}
This way the numbers increase, the label refreshes and shows the new value, while the UI is responsive and for example you can move your form or click on other button.
You should put your UI related codes in an action fired by Invoke to prevent receiving cross thread operation exception.