When I must do many short tasks, that are cooperating with GUI, should I use another BackgroundWorker for each task, or some other solution?
EDIT
I mean update every cell in datagridview (200 rows x 50 columns) every 5 second. Every cell stores image.
BackgroundWorker would be better suited to long running tasks, you want something like ThreadPool. Here's a very crude example:
QueueUserWorkItem allows you to specify a worker method and pass in an object for that method to work on.
ThreadPool.QueueUserWorkItem(new WaitCallback(DoWork), object);
Then you would have your DoWork method where all the magic happens:
public void DoWork(object sender)
{
object s = (object)sender;
this.Invoke(new ThreadDone(ReportProgress), result);
}
Notice the call to this.Invoke(new TaskDone(ReportProgress)); This safely calls code running on the main thread to update your UI with processed data from DoWork. This is done via a private delegate:
private delegate void ThreadDone(object yourObject);
Which would call:
private void ReportProgress(object yourObject)
{
//update UI
}
You could also use this for checking when the task is complete by keeping track of an Interlocked counter object e.g.
foreach (string s in strings)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(DoWork), s);
Interlocked.Increment(ref workItems);
}
And then decrementing the workItems when a single thread completes and make a simple check for when workItems == 0
Interlocked.Decrement(ref workItems);
if (workItems == 0)
{
this.Invoke(new TaskDone(WorkComplete));
}
Hope this helps.
When I'm dealing with many small tasks, I tend to find that the ThreadPool is a nice way of dealing with them. You can dispatch a delegate on a background thread like so:
ThreadPool.QueueUserWorkItem(new WaitCallback(MyThreadProc));
You can also pass an object to the thread as it's state, consider a delegate that takes an object as a parameter. You could call this:
ThreadPool.QueueUserWorkItem(new WaitCallback(MyThreadProc), state);
Where state is some object that your thread knows how to deal with.
Edit: A ThreadPool approach should work just fine for your scenario. Just make sure that any code that changes your GUI will have to be invoked on the GUI thread, or you'll get some cross-thread exceptions.
Related
I have the method below that is running on a separate thread from the main UI thread, and I am trying to update the ListBox control on the main thread. The code does work and the field does get updated, but when the Invoke method runs it switches to the main thread. The problem is that the code after the Invoke also runs on the main thread, but I need it to run on the separate thread.
public static void Status_Message(string str, int destination, int prompt)
{
//Clear_System_Message_Area();
sysmsg++;
ListBox tl = Application.OpenForms["GMLEC"].Controls["groupBox2"].Controls["TestList"] as ListBox;
if (!tl.InvokeRequired)
{
tl.Items.Add(str);
tl.Refresh();
}
else
{
tl.Invoke(new Action<string, int, int>(Status_Message), str, destination, prompt);
}
if (destination == 1)
{
Printer.Output(str);
}
if (prompt == 1)
{
Pause(false);
}
if (sysmsg > 23)
{
Pause(true);
}
}
Is there a way to make it go back to the separate thread?
If you don't want code run on the UI thread, don't invoke the method that contains it.
For what it's worth, I disagree with any code that uses InvokeRequired. First of all, you ought to know from the context whether invoke is required or not. If you don't know which thread the code that's executing is on, then there is too much coupling between the UI and background task parts of the code.
But secondly, the Control.Invoke() method has to check which thread is current anyway, because it has to work whether you are on the UI thread or not. You can always call it safely from the UI thread, and when you do, it can't go queueing up your delegate for invocation and then waiting for it, because that would deadlock. It has to just invoke the delegate directly, but only in that case, which means it's doing the InvokeRequired check anyway.
So, taking all of that into account, just write your code to always invoke the part that needs invoking, and be done with it.
For example:
public static void Status_Message(string str, int destination, int prompt)
{
//Clear_System_Message_Area();
sysmsg++;
ListBox tl = Application.OpenForms["GMLEC"].Controls["groupBox2"].Controls["TestList"] as ListBox;
tl.Invoke((MethodInvoker)(() =>
{
tl.Items.Add(str);
tl.Refresh();
}));
if (destination == 1)
{
Printer.Output(str);
}
if (prompt == 1)
{
Pause(false);
}
if (sysmsg > 23)
{
Pause(true);
}
}
Now, some other notes about this:
It's doubtful that you should be calling Refresh(). Let Winforms deal with updating on its own. If you've somehow interfered with it refreshing the window normally, fix that. Don't hack around it by calling Refresh() yourself.
It's almost certain that there's a better way to encapsulate the ListBox object than by always looking it up from the top of the UI control graph. For example, maybe the actual object should have been referenced directly (e.g. from a TestList field) and passed to the code that will eventually need it.
Finally, and most important, the fact that you're using Invoke() at all is a big warning flag in modern code. There's a decent chance that your overall code could be refactored to use async/await in a way that allows it to read more naturally and still work correctly, but at the very least it would be better to use Progress<T> to mediate cross-thread updates like this.
To address any of these issues would be beyond the scope of the current question, but I do encourage you to take the suggestions under consideration.
This might help...
normally I use Invoke() to activate a part of the script after a certain time. Invoke() Does NOT repeat, if you want it to repeat you can use InvokeRepeating().
another option is to use "Multi-Threading". Here's how to use Multi-Threading:
using System.Threading
public static Thread newThread = new Thread(MultiThread)
private void Start()
{
newThread.Start()
//also newThread.Abort() to quit the thread
}
private static void MultiThread()
{
// this is the seporate thread
// i normally use this for a "while (True)" loop cause it will stop responding
//otherwise
}
srry for any typos
Hopefully this helps
I need to invoke this: string input_ip_r = listView1.Items[lc].SubItems[1].Text;
so I used
if (InvokeRequired)
{
this.Invoke(new MethodInvoker(function));
return;
}
This worked but now I have put it into a BackgroundWorker and using this
if (InvokeRequired)
{
this.Invoke(new MethodInvoker(bw.RunWorkerAsync));
return;
}
it gives an error that you can only run BackgroundWorker one at a time.
So how do I invoke while in the Backgroundworker?
1) Don't put RunWorkerAsync as the method to invoke. It's not actually running the method that you think. What you should really put there is something like this:
this.Invoke(new MethodInvoker(MethodToUpdateUI));
MethodToUpdateUI should be some new method that you create that specifically does whatever UI updates should be made in this context.
2) There's no need for InvokeRequired. You're in a background thread. Invoking will always be required.
To be honest, the entire patter of if(invoke required) call myself else do stuff is an odd construct which I dislike. InvokeRequired should pretty rarely be used. You should almost always know whether you're in the UI thread or a background thread, if you don't, chances are something wrong (either you're always in one or the other and you just don't know which, or it shouldn't be non-deterministic). Usually this means having methods that must be run in the UI thread. If you're already in the UI thread you just call them, if you're in a background thread and know it then you call Invoke first.
On top of that, Invoke works just fine even if you call it when you're already in the UI thread, so there's really no significant negative consequences to just calling Invoke regardless of whether you're in a background thread or already in the UI thread.
3) Usually it's best to separate code for solving business problems from UI code. It's code smell to be invoking from within DoWork's handler. If this is right near the end, you should probably be adding an event handler to RunWorkerCompleted. If you're calling this periodically to update the UI with progress of the worker, you should be using ReportProgress and handling the ProgressReported event. For getting info from the UI for use in a long running task you should access it before starting the background task. For exceptional cases that aren't any of those, it may be appropriate to use Invoke, but the remaining cases ought to be rare.
I'm not quite sure how you want to use the values, but just to give you an example, you could easily just do this in the BackgroundWorker thread:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
string input_ip_r = "";
this.Invoke(new Action(() =>
{
// Don't know what "lc" is (a loop variable?)
input_ip_r = listView1.Items[lc].SubItems[1].Text;
}));
}
See this answer for other ways of doing the same (this is for >= .Net 3.5)
When calling BeginInvoke(), will the delegates comes back in the same order that the method is being called? or there is no guarantee which delegates will come back first?
public Form1()
{
InitializeComponent();
for (int i = 0; i < 100; i++)
{
Thread t = new Thread(DisplayCount);
t.Start(i);
}
}
public void DisplayCount(object count)
{
if (InvokeRequired)
{
BeginInvoke(new Action<object>(DisplayCount), count);
return;
}
listBox1.Items.Add(count);
}
And list of integers will come back out of order.
Control.BeginInvoke() will execute the action asynchronously, but on the UI thread.
If you call BeginInvoke() multiple times with different actions, they will come back in order of whichever ones complete the fastest.
As a side-note, you should probably use some sort of snychronization mechanism around your listBox1.Items.Add(count) calls, perhaps locking on its SynchRoot property.
From MSDN - ListBox.ObjectCollection Class
Any public static (Shared in Visual Basic) members of this type are
thread safe. Any instance members are not guaranteed to be thread
safe.
(Emphasis added)
If you call the same function multiple times, then they should come back in the same order, maybe! If you have a function analysing a 1 TB Dataset and another function just doing some Logging then I don't think they will came back in the same order.
It also depends on the DispatcherPriority you have set for BeginInvoke. A low priority like SystemIdl will be executet later then a higher priority like Send.
If you start a thread using Thread.Start() then the execution of the Thread-Function happens asynchronously at a random time after that call.
That's why you get random numbers in my opinion.
I have a rather large class which contains plenty of fields (10+), a huge array (100kb) and some unmanaged resources. Let me explain by example
class ResourceIntensiveClass
{
private object unmaganedResource; //let it be the expensive resource
private byte[] buffer = new byte[1024 * 100]; //let it be the huge managed memory
private Action<ResourceIntensiveClass> OnComplete;
private void DoWork(object state)
{
//do long running task
OnComplete(this); //notify callee that task completed so it can reuse same object for another task
}
public void Start(object dataRequiredForCurrentTask)
{
ThreadPool.QueueUserWorkItem(DoWork); //initiate long running work
}
}
The problem is that the start method never returns after the 10000th iteration causing a stack overflow. I could execute the OnComplete delegate in another thread giving a chance for the Start method to return, but it requires using extra cpu time and resources as you know. So what is the best option for me?
Is there a good reason for doing your calculations recursively? This seems like a simple loop would do the trick, thus obviating the need for incredibly deep stacks. This design seems especially problematic as you are relying on main() to setup your recursion.
recursive methods can get out of hand quite fast. Have you looked into using Parallel Linq?
you could do something like
(your Array).AsParallel().ForAll(item => item.CallMethod());
you could also look into the Task Parallel Library (TPL)
with tasks, you can define an action and a continue with task.
The Reactive Framework (RX) on the other hand could handle these on complete events in an async manner.
Where are you changing the value of taskData so that its length can ever equal currentTaskIndex? Since the tasks you are assigning to the data are never changing, they are being carried out forever...
I would guess that the problem arises from using the pre-increment operator here:
if(c.CurrentCount < 10000)
c.Start(++c.CurrentCount);
I am not sure of the semantics of pre-increment in C#, perhaps the value passed to a method call is not what you expect.
But since your Start(int) method assigns the value of the input to this.CurrentCount as it's first step anyway, you should be safe replacing this with:
if(c.CurrentCount < 10000)
c.Start(c.CurrentCount + 1);
There is no point in assigning to c.CurrentCount twice.
If using the threadpool, I assume you are protecting the counters (c.CurrentCount), otherwise concurrent increments will cause more activity, not just 10000 executions.
There's a neat tool called a ManualResetEvent that could simplify life for you.
Place a ManualResetEvent in your class and add a public OnComplete event.
When you declare your class, you can wire up the OnComplete event to some spot in your code or not wire it up and ignore it.
This would help your custom class to have more correct form.
When your long process is complete (I'm guessing this is in a thread), simply call the Set method of the ManualResetEvent.
As for running your long method, it should be in a thread that uses the ManualResetEvent in a way similar to below:
private void DoWork(object state)
{
ManualResetEvent mre = new ManualResetEvent(false);
Thread thread1 = new Thread(
() => {
//do long running task
mre.Set();
);
thread1.IsBackground = true;
thread1.Name = "Screen Capture";
thread1.Start();
mre.WaitOne();
OnComplete(this); //notify callee that task completed so it can reuse same object for another task
}
When you data bind in C#, the thread that changes the data causes the control to change too. But if this thread is not the one on which the control was created, you'll get an Illegal Cross Thread Operation exception.
Is there anyway to prevent this?
You should be able to do something like:
if (control.InvokeRequired)
{
control.Invoke(delegateWithMyCode);
}
else
{
delegateWithMyCode();
}
InvokeRequired is a property on Controls to see if you are on the correct thread, then Invoke will invoke the delegate on the correct thread.
UPDATE: Actually, at my last job we did something like this:
private void SomeEventHandler(Object someParam)
{
if (this.InvokeRequired)
{
this.Invoke(new SomeEventHandlerDelegate(SomeEventHandler), someParam);
}
// Regular handling code
}
which removes the need for the else block and kind of tightens up the code.
As I don't have a test case to go from I can't guarantee this solution, but it seems to me that a scenario similar to the one used to update progress bars in different threads (use a delegate) would be suitable here.
public delegate void DataBindDelegate();
public DataBindDelegate BindData = new DataBindDelegate(DoDataBind);
public void DoDataBind()
{
DataBind();
}
If the data binding needs to be done by a particular thread, then let that thread do the work!
If the thread call is "illegal" (i.e. the DataBind call affects controls that were not created in the thread it is being called from) then you need to create a delegate so that even if the decision / preparation for the DataBind is not done in the control-creating thread, any resultant modification of them (i.e. DataBind()) will be.
You would call my code from the worker thread like so:
this.BindData.Invoke();
This would then cause the original thread to do the binding, which (presuming it is the thread that created the controls) should work.
In WPF and Silverlight the binding infrastructure takes care of the switching to the UI thread.