I've been looking all around to find someone with a similar issue, but did not find anything. I'm coding a C# application using WPF UI.
To update the progressbar, I cannot use multithreading like I used to (in CLI) because it's telling me that I cannot update UI elements if it does not come from the main thread.
One solution is to create background workers. I've implemented this solution and it works well, but I want the tasks to be divided between more workers/threads (multithreading) in order to be more efficient.
I do not know the direction I have to take. If anyone can orient me with this issue, it would be more welcome.
Here is my code : (used to code with a MVVM pattern, just here to paste my code it's simpler for you)
public partial class testFunctionTaskPanel: Page
{
private BackgroundWorker backgroundWorker1 = new BackgroundWorker();
private string myURL;
public testFunctionTaskPanel()
{
InitializeComponent();
}
private void startButton_Click(object sender, RoutedEventArgs e)
{
myURL = myURL.Text;
myResults.Items.Clear();
myResults.Items.Add("----Starting----");
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.ProgressChanged += ProgressChanged;
backgroundWorker1.DoWork += DoWork;
backgroundWorker1.RunWorkerCompleted += BackgroundWorker_RunWorkerCompleted;
backgroundWorker1.RunWorkerAsync();
}
private void DoWork(object sender, DoWorkEventArgs e)
{
int length = myLoadedList.Items.Count;
for (int i = 1; i <= length; i++)
{
try
{
HttpRequest req = new HttpRequest();
req.Proxy = null;
req.ConnectTimeout = 5000;
req.IgnoreProtocolErrors = true;
string get = myURL + myLoadedList.Items[i].ToString();
var response = req.Get(get);
if (response.StatusCode == Leaf.xNet.HttpStatusCode.OK)
{
this.Dispatcher.Invoke(() =>
{
myResults.Items.Add(myLoadedList.Items[i].ToString());
});
}
}
catch{}
backgroundWorker1.ReportProgress(i);
}
}
private void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
myResults.Items.Add("----Finish----");
}
private void ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// This is called on the UI thread when ReportProgress method is called
progressbar.Value = e.ProgressPercentage;
}
}