I am trying to get a ProgressBar with the progress of a dataset being converted to Excel using the BackgroundWorker. The problem is that the work is being done in a different class than the ProgressBar and I am having difficulty calling worker.ReportProgress(...) from within my loop. I am sorry if this is a easy thing but I am new to C# and have been trying this the whole day and just can't seem to get it right. Your help would be HIGHLY appreciated.
namespace CLT
{
public partial class GenBulkReceipts : UserControl
{
private void btnOpen_Click(object sender, EventArgs e)
{
Cursor.Current = Cursors.WaitCursor;
try
{
OpenFile();
}
Cursor.Current = Cursors.Default;
}
private void OpenFile()
{
if (dsEx1.Tables[0].Rows.Count > 0)
{
backgroundWorker1.RunWorkerAsync(dsEx1);
}
}
public void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
DataSet ImportDataSet = e.Argument as DataSet;
AccountsToBeImported = new BLLService().Get_AccountsToBeReceipted(ImportDataSet);
}
public void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.progressBar1.Value = e.ProgressPercentage;
}
// ...
}
}
namespace BLL
{
class GenBulkReceiptsBLL
{
public DataSet Get_AccountsToBeReceipted(DataSet dsImport)
{
DataSet dsReturn = AccountsDAL.QGenReceiptAccounts(0,0,"");//Kry Skoon DataSet wat ge-populate moet word
CLT.GenBulkReceipts pb = new CLT.GenBulkReceipts();
int TotalRows = dsImport.Tables[0].Rows.Count;
//pb.LoadProgressBar(TotalRows);
int calc = 1;
int ProgressPercentage;
foreach (DataRow dr in dsImport.Tables[0].Rows)
{
ProgressPercentage = (calc / TotalRows) * 100;
//This is the problem as I need to let my Progressbar progress here but I am not sure how
//pb.worker.ReportProgress(ProgressPercentage);
}
return dsReturn;
}
// ...
}
}
You'll need to pass your worker to the Get_AccountsToBeReceipted method - it can then call BackgroundWorker.ReportProgress:
// In GenBulkReceipts
public void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
DataSet importDataSet = e.Argument as DataSet;
AccountsToBeImported =
new BLLService().Get_AccountsToBeReceipted(importDataSet, worker);
}
// In GenBulkReceiptsBLL
public DataSet Get_AccountsToBeReceipted(DataSet dsImport,
BackgroundWorker worker)
{
...
worker.ReportProgress(...);
}
Alternatively, you could make GenBulkReceiptsBLL have its own Progress event, and subscribe to that from GenBulkReceipts - but that would be more complicated.
Your class GenBulkReceiptsBLL needs some reference to the BackgroundWorker instance. You can achieve this in a variety of ways. One such suggestion would be to pass the reference to the class when instantiating it.
For example, since GenBulkReceipts is the class that instantiates GenBulkReceiptsBLL, then in the constructor for GenBulkReceiptsBLL, you could pass the instance of the BackgroundWorker that is currently being used in GenBulkReceipts. This would allow for you to call ReportProcess(...) directly. Alternately, you could pass the reference directly into the Get_AccountsToBeReceipted(...) method.
Related
I have several textboxes in my wpf application. The LostFocus-Event of each textbox starts a backgroundworker to send the data to a connected serial port.
private readonly BackgroundWorker online_mode_send_worker = new BackgroundWorker();
online_mode_send_worker.DoWork += online_mode_send_worker_DoWork;
online_mode_send_worker.RunWorkerCompleted += online_mode_send_worker_RunWorkerCompleted;
private void TextBox_LostFocus(object sender, RoutedEventArgs e)
{
online_mode_send_worker.RunWorkerAsync(data);
}
private void online_mode_send_worker_DoWork(object sender, DoWorkEventArgs e)
{
List<object> data = (List<object>)e.Argument;
Port.WriteLine(STARTCHARACTER + XMLSET + XML_TAG_START + data[0] + XML_TAG_STOP + data[1] + ENDCHARACTER);
string received = Port.ReadLine();
}
private void online_mode_send_worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//do some things after worker completed
}
At this point, everything is working fine.
But sometimes I have to send two data-points directly after each other and there I have a problem.
private void TextBox_LostFocus(object sender, RoutedEventArgs e)
{
online_mode_send_worker.RunWorkerAsync(data1);
//wait until backgroundworker has finished
online_mode_send_worker.RunWorkerAsync(data2);
}
The Backgroundworker is still running and I get an exception thrown.
Is it possible to wait after the first online_mode_send_worker.RunWorkerAsync(data) until it has finished and then start the second online_mode_send_worker.RunWorkerAsync(data)?
while(online_mode_send_worker.isBusy); is not working because the main-thread is blocking and the RunWorkerCompleted() is not thrown and so the Backgroundwoker is always busy.
I have found something like this, but Application.DoEvents() is not available in wpf.
while (online_mode_send_worker.IsBusy)
{
Application.DoEvents();
System.Threading.Thread.Sleep(100);
}
Here is a rough idea of what I mentioned in the comments.
public class Messenger {
private readonly BackgroundWorker online_mode_send_worker = new BackgroundWorker();
private readonly ConcurrentQueue<object> messages;
public Messenger() {
messages = new ConcurrentQueue<object>();
online_mode_send_worker.DoWork += online_mode_send_worker_DoWork;
online_mode_send_worker.RunWorkerCompleted += online_mode_send_worker_RunWorkerCompleted;
}
public void SendAsync(object message) {
if (online_mode_send_worker.IsBusy) {
messages.Enqueue(message);
} else {
online_mode_send_worker.RunWorkerAsync(message);
}
}
public Action<object> MessageHandler = delegate { };
private void online_mode_send_worker_DoWork(object sender, DoWorkEventArgs e) {
if (MessageHandler != null)
MessageHandler(e.Argument);
}
private void online_mode_send_worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
object nextMessage = null;
if (messages.Count > 0 && messages.TryDequeue(out nextMessage)) {
online_mode_send_worker.RunWorkerAsync(nextMessage);
}
}
}
You have a queue to hold on to messages that were sent while the background worker was busy and have the worker check the queue for any pending messages when it has completed doing its work.
The messenger can be used like this.
private Messenger messenger = new Messenger();
private void Initialize() { //I would expect this to be in the constructor
messenger.MessageHandler = MessageHandler;
}
private void TextBox_LostFocus(object sender, RoutedEventArgs e)
{
messenger.SendAsync(data);
}
private void MessageHandler(object message)
{
List<object> data = (List<object>)message;
Port.WriteLine(STARTCHARACTER + XMLSET + XML_TAG_START + data[0] + XML_TAG_STOP + data[1] + ENDCHARACTER);
string received = Port.ReadLine();
}
It seems that I missed the serial stuff. So what you want to do is synchronize your asynchronuouscalls:
private void Button_Click(object sender, RoutedEventArgs e)
{
Task.Run(() => mySerialDevice1.WriteData(data1));
Task.Run(() => mySerialDevice1.WriteData(data2));
}
public class SerialDevice
{
public Port Port { get; set; }
public object _LockWriteData = new object();
public void WriteData(string data)
{
lock(_LockWriteData)
{
Port.WriteLine(data);
}
}
}
also see:
https://msdn.microsoft.com/en-us/library/c5kehkcz.aspx
https://msdn.microsoft.com/en-us/library/de0542zz(v=vs.110).aspx
ORIGINAL ANSWER
You can use Task instead of Backgroundworker.
private void Button_Click(object sender, RoutedEventArgs e)
{
Task.Run(() => OnlineModeSendData(data1));
Task.Run(() => OnlineModeSendData(data2));
}
private void OnlineModeSendData(List<string> data)
{
Port.WriteLine(STARTCHARACTER + XMLSET + XML_TAG_START + data[0]+ XML_TAG_STOP + data[1] + ENDCHARACTER);
string received = Port.ReadLine();
}
I also would like to suggest that you make real objects instead of passing string arrays as arguments.
For Example send BlinkLedRequest:
public class BlinkLedRequest
{
public int LedId{get;set;}
public int DurationInMilliseconds {get;set}
}
and a corresponding method:
public void SendBlinkLed(BlickLedRequest request)
{
....
}
I think your should use RunWorkerCompleted event and add a delegate:
online_mode_send_worker.RunWorkerCompleted += (s, ev) =>
{
if (ev.Error != null)
{
//log Exception
}
//if(conditionToBrake)
// return;
online_mode_send_worker.RunWorkerAsync(data2);
};
online_mode_send_worker.RunWorkerCompleted(data1);
Make sure you put there a condition to avoid infinite loop.
I'd say that if you MUST wait until after the first "job" is done, that what you want is Task.ContinueWith() and change your interface accordingly. The msdn page is good for it IMO, but watch out that you're waiting on the "correct" task object. Hint: it's the return value of ContinueWith() that you should call Wait() on. This is a good pattern to do for launching a Task and then waiting for it later as long as you can keep the Task that is returned so you can wait on it.
For a more generic "I only want one background thread doing things in the order they're added, and I want to wait until they're ALL done and I know when I'm done adding." I would suggest using a BlockingCollection<Action> with only one thread consuming them. An example of how to do that is found in this other answer.
Update:
bw.RunWorkerAsync(data1);
//wait here
bw.RunWorkerAsync(data2);
Is not good aproach, because UI will be blocked on time of waiting. Better:
bw.RunWorkerAsync(new object[] { data1, data2 }); //or new object[] { data1 } if no data2
Original answer:
I advice not to use construction: while (bw.Busy) { ... } (it consumes cpu time), use synchronization objects, for example, ManualResetEvent
BackgroundWorker is great class, but does not support waiting. Just create addition object for waiting:
var bw = new BackgroundWorker();
bw.DoWork += Bw_DoWork;
bw.RunWorkerCompleted += Bw_RunWorkerCompleted;
bool wasError;
ManualResetEvent e = null;
private void TextBox_LostFocus(object sender, RoutedEventArgs e)
{
if (e != null)
return;
wasError = false;
e = new ManualResetEvent(false); //not signaled
bw.RunWorkerAsync(data1);
e.Wait(); //much better than while(bw.Busy())
if (!wasError)
bw.RunWorkerAsync(data2);
e = null;
}
private void Bw_DoWork(object sender, DoWorkEventArgs e)
{
//background work in another thread
}
private void Bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
//catch exception here
wasError = true;
}
e.Set(); //switch to signaled
}
If you need only call twice you can do this:
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
online_mode_send_worker.RunWorkerAsync(data2);
}
But if you need to queue commands you need rewrite in another way Using Task.
One Task where inside it you will have a for-loop where you will send your data through serial port sequentially.
https://msdn.microsoft.com/pt-br/library/system.threading.tasks.task(v=vs.110).aspx
I am copying large files from one place to another.
It is taking a long time so I decided to use a progress bar.
I am following this example.
The copyItems() function iterates through the list items and copies the items from another place. It in turn calls a function CopyListItem which copies one item .
I need to tie the backgroundWorker1.ReportProgress(i) to the total no of items i.e. itemcoll.
I do not want to use thread.sleep() .
The progress bar needs to show the actual time required to copy the file from one place to another.
The Progress bar needs to progress when only when one file is copied.
IT needs to complete when all the files are copied
using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, System.EventArgs e)
{
// Start the BackgroundWorker.
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 1; i <= itemscoll.count; i++)
{
// Wait 100 milliseconds.
Thread.Sleep(100);
// Report progress.
backgroundWorker1.ReportProgress(i);
}
}
private void CopyListItem(SPListItem sourceItem, string destinationListName, string destServerURL)
{
// copy items
}
private void copyitems()
{
try
{
int createdYear = 0;
backgroundWorker1.RunWorkerAsync();
foreach (SPListItem sourceItem in itemscoll)
{
if (Helper.year == createdYear)
{
CopyListItem(sourceItem, Helper.destinationListName,Helper.destServerURL);
DeleteItem(CompRefNo);
}
}
}
catch()
{}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// Change the value of the ProgressBar to the BackgroundWorker progress.
progressBar1.Value = e.ProgressPercentage;
// Set the text.
this.Text = e.ProgressPercentage.ToString();
}
}
}
You need to do your copy-action in the DoWork-Event of the BackgroundWorker. So when you call the backgroundWorker1.RunWorkerAsync() you'll have to pass an object to it containing all the needed informations. This could be something like:
internal class WorkerItem
{
public WorkerItem(List<SPListItem> spListItems, string destinationListName, string destinationServerURL)
{
SPListItems = new List<SPListItem>(spListItems);
DestinationListName = destinationListName;
DestinationServerURL = destinationServerURL;
}
public List<SPListItem> SPListItems { get; private set; }
public string DestinationListName { get; private set; }
public string DestinationServerURL { get; private set; }
}
The call of RunWorkerAsync can look something like:
backgroundWorker1.RunWorkerAsync(new WorkerItem(...));
In your DoWork-Handler you than have to get this object from the e.Argument and cast it to WorkerItem. Than you can work with it like:
private void BackgroundWorker1OnDoWork(object sender, DoWorkEventArgs e)
{
WorkerItem workerItem = (WorkerItem)e.Argument;
for (int i = 0; i < workerItem.SPListItems.Count(); i++)
{
// CopyListItem is doing the copy for one item.
CopyListItem(workerItem.SPListItems[i], workerItem.DestinationListName, workerItem.DestinationServerURL);
((BackgroundWorker)sender).ReportProgress(i + 1);
}
}
The ProgressChanged-Handler only increments the value of the ProgressBar:
private void BackgroundWorker1OnProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
If you want to have more informations in the ProgressChanged-Handler you can pass an additional object as UserState. This you can get by object additional = e.UserState;
Right before you call backgroundWorker1.RunWorkerAsync(new WorkerItem(...)) you should set the Maximum of progressBar1 to the amount of SPListItems like:
progressBar1.Maximum = itemscoll.Count;
Your BackgroundWorker only reports it's progress to you if you set.
backgroundWorker1.WorkerReportsProgress = true;
If you want to be informed when the BackgroundWorker is finished you can get the RunWorkerCompleted-Event.
backgroundWorker1.RunWorkerCompleted += BackgroundWorker1OnRunWorkerCompleted;
I have an application that takes a Wireshark capture file and feeds it (all the containing packets) into a network adapter.
Currently my application is a big mess - countless global variables & every task opened within a seperate BackgroundWorker instance etc...
To clarify - the purpose of using BackgroundWorkers here (more specifically the DoWork, RunWorkerCompleted events and the WorkerReportsProgress property) is to prevent the packet feeding operations from freezing my UI. To stop an operation, I need access to these workes - for now, global variables are used to achieve this.
So the question is - should I place my BackgroundWorker objects inside a Singleton-type class and then call this object when necessary?
From a technical point of view is possible, after all the singleton pattern is a design pattern that restricts the instantiation of a class to one object
you can try something like this
public class BackWorkerSingleton
{
private BackgroundWorker _backgroundWorker;
private static readonly object myLock = new object();
private static BackWorkerSingleton _backWorkerSingleton = new BackWorkerSingleton();
public delegate void ReportProgressEventHandler(object sender,MyEventsArgs e);
public event ReportProgressEventHandler ReportProgress = delegate{ };
private BackWorkerSingleton()
{
_backgroundWorker = new BackgroundWorker();
_backgroundWorker.DoWork += new DoWorkEventHandler(_backgroundWorker_DoWork);
_backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(_backgroundWorker_ProgressChanged);
}
void _backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.ReportProgress( this, new MyEventsArgs(){Progress = e.ProgressPercentage});
}
void _backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
// do your work here
}
public void StartTheJob()
{
_backgroundWorker.RunWorkerAsync();
}
public static BackWorkerSingleton Worker
{
get
{
lock (myLock)
{
if (_backWorkerSingleton == null)
{
_backWorkerSingleton = new BackWorkerSingleton();
}
}
return _backWorkerSingleton;
}
}
}
class MyEventsArgs:EventArgs
{
public int Progress { get; set; }
}
and here the report progress
private void Form1_Load(object sender, EventArgs e)
{
BackWorkerSingleton.Worker.ReportProgress += new BackWorkerSingleton.ReportProgressEventHandler(Worker_ReportProgress);
}
void Worker_ReportProgress(object sender, MyEventsArgs e)
{
}
and call it like this
BackWorkerSingleton.Worker.StartJob()
How do I use Threading to Change some Cell in Gridview? I have a query from database and it uses a lot of time for its query. So It's very slow and I would like to use Threading to load data faster. Also, when the thread has finished it's job can change data in Grid view?
using System.Threading;
using System.Threading.Tasks;
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
dataGridView1.DataSource = new List<Test>() { new Test { Name = "Original Value" } };
}
// Start the a new Task to avoid blocking the UI Thread
private void button1_Click(object sender, EventArgs e)
{
Task.Factory.StartNew(this.UpdateGridView);
}
// Blocks the UI
private void button2_Click(object sender, EventArgs e)
{
UpdateGridView();
}
private void UpdateGridView()
{
//Simulate long running operation
Thread.Sleep(3000);
Action del = () =>
{
dataGridView1.Rows[0].Cells[0].Value = "Updated value";
};
// If the caller is on a different thread than the one the control was created on
// http://msdn.microsoft.com/en-us/library/system.windows.forms.control.invokerequired%28v=vs.110%29.aspx
if (dataGridView1.InvokeRequired)
{
dataGridView1.Invoke(del);
}
else
{
del();
}
}
}
my aim is that in the function "Dummy" i can change the controls like labels etc of the form from which the thread is initiating..how to do it..please don't suggest completely different strategies or making a worker class etc...modify this if you can
Thread pt= new Thread(new ParameterizedThreadStart(Dummy2));
private void button1_Click(object sender, EventArgs e)
{
pt = new Thread(new ParameterizedThreadStart(Dummy2));
pt.IsBackground = true;
pt.Start( this );
}
public static void Dummy(........)
{
/*
what i want to do here is to access the controls on my form form where the
tread was initiated and change them directly
*/
}
private void button2_Click(object sender, EventArgs e)
{
if (t.IsAlive)
label1.Text = "Running";
else
label1.Text = "Dead";
}
private void button3_Click(object sender, EventArgs e)
{
pt.Abort();
}
}
}
what i plan is that i could do this in the "Dummy" function
Dummy( object p)
{
p.label1.Text = " New Text " ;
}
You could do this, supposing you're passing an instance of the form to the thread method using the t.Start(...) method:
private void Form_Shown(object sender)
{
Thread t = new Thread(new ParameterizedThreadStart(Dummy));
t.Start(this);
}
....
private static void Dummy(object state)
{
MyForm f = (MyForm)state;
f.Invoke((MethodInvoker)delegate()
{
f.label1.Text = " New Text ";
});
}
EDIT
Added thread start code for clarity.
You can't do this. You can only access a UI control on the same thread that created it.
See the System.Windows.Forms.Control.Invoke Method and the Control.InvokeRequired property.
Can use something like this:
private void UpdateText(string text)
{
// Check for cross thread violation, and deal with it if necessary
if (InvokeRequired)
{
Invoke(new Action<string>(UpdateText), new[] {text});
return;
}
// What the update of the UI
label.Text = text;
}
public static void Dummy(........)
{
UpdateText("New text");
}