How to invoke components - c#

In my apps i use backgroundWorker, to set text in some TextBox, I need first to invoke that TextBox.
First I use:
if (someTextBox.InvokeRequired)
{
someTextBox.Invoke((MethodInvoker)delegate
{
someTextBox.Text = "some_text";
});
}
else
{
someTextBox.Text = "some_text";
}
This method work for me fine, but because i have multiple TextBox-es i wrote:
private void invComp(TextBox txtBox, String str)
{
if (txtBox.InvokeRequired)
{
txtBox.Invoke((MethodInvoker)delegate
{
txtBox.Text = str;
});
}
else
{
txtBox.Text = str;
}
}
It is better to invoke it on this way? (invComp(someTextBox, "some_text");
Or maybe i have some third, bether , way?
I invoke some buttons to, I was think to write something like this for button to, if this is ok?
Tnx

Control.InvokeRequired suffers from cargo cult. You are updating a control from a worker thread, you know that invoking is required. So there is absolutely no point in testing it. Except for one reason, there is something fundamentally wrong when it is false. Which happens a lot more often than programmers like, forgetting to stop a worker when the user closes the window is a traditional bug. This causes all kind of mayhem, you want to know about it:
private void invComp(TextBox txtBox, String str) {
if (!this.InvokeRequired) throw new InvalidOperationException("You forgot to stop the worker");
this.BeginInvoke(new Action(() => txtBox.Text = str));
}
Short and snappy and fail-safe and fast. Good qualities of code. Note that it uses the form's BeginInvoke() method, it doesn't depend on a child control being created. And that it uses BeginInvoke() instead of Invoke(), important to not bog down the worker thread and avoid deadlock. Always avoid Invoke(), it is only required when you need to know a method return value.
A completely different take is to focus on you using BackgroundWorker. It already marshals calls to the UI thread, it is just that the method has a clumsy name. You can get the ProgressChanged event to execute any code, it isn't just good enough to show progress. Write your event handler like this:
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) {
((Action)e.UserState).Invoke();
}
Now you can make it execute any code on the UI thread:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) {
var worker = (BackgroundWorker)sender;
//...
worker.ReportProgress(0, new Action(() => textBox1.Text = "hello"));
}

You can slightly modify your method, to make it generic, so that you can use if for any control.
private void invComp<T>(T control, String str) where T: Control
{
if (control.InvokeRequired)
{
control.Invoke((MethodInvoker)delegate
{
control.Text = str;
});
}
else
{
control.Text = str;
}
}

Related

Need to implement "Scan" method in dll (non blocking)

Sorry for the title, i didn't find it easy to resume.
My issue is that I need to implement a c# dll that implements a 'scan' method, but this scan, when invoked, must not block the main thread of the application using the dll. Moreover, it is a duty that after the scan resolves it rises an Event.
So my issue (in the deep) is that i'm not so experienced at c#, and after very hard investigation i've come up with some solutions but i'm not very sure if they are the "right" procedures.
In the dll i've come up with:
public class Reader
{
public delegate void ReaderEventHandler(Object sender, AlertEventArgs e);
public void Scan(String ReaderName)
{
AlertEventArgs alertEventArgs = new AlertEventArgs();
alertEventArgs.uuiData = null;
//Code with blocking scan function here
if (ScanFinnished)
{
alertEventArgs.uuiData = "Scan Finnished!";
}
alertEventArgs.cardStateData = readerState[0].eventState;
ReaderEvent(new object(), alertEventArgs);
}
public event ReaderEventHandler ReaderEvent;
}
public class AlertEventArgs : EventArgs
{
#region AlertEventArgs Properties
private string _uui = null;
private uint cardState = 0;
#endregion
#region Get/Set Properties
public string uuiData
{
get { return _uui; }
set { _uui = value; }
}
public uint cardStateData
{
get { return cardState; }
set { cardState = value; }
}
#endregion
}
While in the main app I do:
Reader reader;
Task polling;
String SelectedReader = "Some_Reader";
private void bButton_Click(object sender, EventArgs e)
{
reader = new Reader();
reader.ReaderEvent += new Reader.ReaderEventHandler(reader_EventChanged);
polling = Task.Factory.StartNew(() => reader.Scan(SelectedReader));
}
void reader_EventChanged(object sender, AlertEventArgs e)
{
MessageBox.Show(e.uuiData + " Estado: " + e.cardStateData.ToString("X"));
reader.Dispose();
}
So here, it works fine but i don't know if it's the proper way, in addition i'm not able to handle possible Exceptions generated in the dll.
Also tried to use async/await but found it difficult and as I understand it's just a simpler workaround Tasks.
What are the inconvinients of this solution? how can i capture Exceptions (are they in other threads and that's why i cant try/catch them)? Possible concept faults?
When your class sends events, the sender usually is that class, this. Having new object() as sender makes absolutely no sense. Even null would be better but... just use this.
You shouldn't directly raise events as it might result in race conditions. Might not happen easily in your case but it's just a good guideline to follow. So instead of calling ReaderEvent(new object(), alertEventArgs); call RaiseReaderEvent(alertEventArgs); and create method for it.
For example:
private void RaiseReaderEvent(AlertEventArgs args)
{
var myEvent = ReaderEvent; // This prevents race conditions
if (myEvent != null) // remember to check that someone actually subscribes your event
myEvent(this, args); // Sender should be *this*, not some "new object()".
}
Though I personally like a bit more generic approach:
private void Raise<T>(EventHandler<T> oEvent, T args) where T : EventArgs
{
var eventInstance = oEvent;
if (eventInstance != null)
eventInstance(this, args);
}
Which can then be used to raise all events in same class like this:
Raise(ReaderEvent, alertEventArgs);
Since your scan should be non-blocking, you could use tasks, async/await or threads for example. You have chosen Tasks which is perfectly fine.
In every case you must understand that when you are not blocking your application, your application's main thread continues going like a train. Once you jump out of that train, you can't return. You probably should declare a new event "ErrorEvent" that is raised if your scan-procedure catches an exception. Your main application can then subscribe to that event as well, but you still must realize that those events are not (necessarily) coming from the main thread. When not, you won't be able to interact with your GUI directly (I'm assuming you have one due to button click handler). If you are using WinForms, you'll have to invoke all GUI changes when required.
So your UI-thread safe event handler should be something like this:
void reader_EventChanged(object sender, AlertEventArgs e)
{
if (InvokeRequired) // This true for others than UI Thread.
{
Invoke((MethodInvoker)delegate
{
Text = "My new title!";
});
}
else
Text = "My new title!";
}
In WPF there's Dispather that handles similar invoking.

Update process from within method called by backgroundworker c#

I have an application with a gui and a Rich Text Box where I output what the program is currently doing since data processing can be quite long.
I tried two approaches for that:
1 In the Backgroundworker method I can just call the following code fine:
GlobalVar.backgroundWorkerAppendText = task.Build_CSV_List();
Processchange();
Whereas I cannot use Form1.Processchange(); in the helper class due to the non static context
2 Therefore I tried to create my very first eventhandler.
The Idea was that helper.UpdateConsole() would raise an event
public event EventHandler OnConsoleUpdate;
public void Consoleupdate()
{
OnConsoleUpdate(this, EventArgs.Empty);
}
to which the Backgroundworker listens and then calls Processchange from its context
public void BackgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
StandardTasks task = new StandardTasks();
Helper helper = new Helper();
helper.OnConsoleUpdate += Processchange;
task.DoSomeStuffHere()
}
public void Processchange(object sender=null, EventArgs e=null)
{
//MessageBox.Show(GlobalVar.backgroundWorkerAppendText);
GlobalVar.next = false;
backgroundWorker1.ReportProgress(1);
while (GlobalVar.next == false)
{
helper.TimeBreaker(100,"ms");
}
}
Unfortunately this was was not successful. As soon as rising the Event I get the errormessage System.NullReferenceException which -after googling- leads me to the conclusion that there is no listerner attached to the event eventhouh I attached it in the Backgroundworker Do work.
Edit: the OnConsoleUpdate() == null as shown on the screenshot below
event = null
The helper is in another class file "helpers" which might be important for a solution.
i hope you guys can help me out.
Welcome to SO!
A few things immediately jump to mind.
First, let's get the event issue out of the way. You've got the correct approach - you need an event and method to call it, but that method should check if the event is null.
Basically, do this:
public event EventHandler OnConsoleUpdate;
public void ConsoleUpdate()
{
OnConsoleUpdate?.Invoke(this, EventArgs.Empty);
}
The above makes use of ?, a null-condition operator. You can read more about it on this MSDN page.
Second thing... it's unclear what your background worker actually IS. It sounds like it's some kind of custom class you crated? The reason it's important is because .NET actually has a BackgroundWorker class used for running operations... well, in the background. It also has an OnProgressChanged event which you can hook up to which could be used to update the UI (just remember to set the WorkerReportsProgress property to true). And to use the BackgroundWorker mentioned above, you shouldn't need to create any events of your own.
Here's how you can use the standard .NET BackgroundWorker:
System.ComponentModel.BackgroundWorker worker = new System.ComponentModel.BackgroundWorker();
void StartBackgroundTask()
{
worker.DoWork += worker_DoWork;
//if it's possible to display progress, use this
worker.WorkerReportsProgress = true;
worker.ProgressChanged += worker_ProgressChanged;
//what to do when the method finishes?
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
//start!
worker.RunWorkerAsync();
}
void worker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
//perform any "finalization" operations, like re-enable disabled buttons
//display the result using the data in e.Result
//this code will be running in the UI thread
}
//example of a container class to pass more data in the ReportProgress event
public class ProgressData
{
public string OperationDescription { get; set; }
public int CurrentResult { get; set; }
//feel free to add more stuff here
}
void worker_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
//display the progress using e.ProgressPercentage or e.UserState
//this code will be running in the UI thread
//UserState can be ANYTHING:
//var data = (ProgressData)e.UserState;
}
void worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
//this code will NOT be running in the UI thread!
//you should NOT call the UI thread from this method
int result = 1;
//perform calculations
for (var i = 1; i <= 10; i++)
{
worker.ReportProgress(i, new ProgressData(){ OperationDescription = "CustomState passed as second, optional parameter", CurrentResult = result });
System.Threading.Thread.Sleep(TimeSpan.FromSeconds(5));
result *= i;
}
e.Result = result;
}
Now, the thing about the BackgroundWorker class is that it is rather old, and with current .NET versions you can use the async / await keywords to easily handle background operations and UI updates, but this probably is going outside the bounds of this question. That said, the existence of async / await doesn't invalidate the use of BackgroundWorker which is pretty simple in its usage.
There's one more worrisome thing in your code.
public void BackgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
StandardTasks task = new StandardTasks(); //<- you create a task
Helper helper = new Helper(); // <- you create a helper
helper.OnConsoleUpdate += Processchange; // <- you hook up to the helper event
task.DoSomeStuffHere(); // <- you do stuff with the task... but the task doesn't know about your helper above! Does `StandardTasks` use `Helper`? If so, how?
}
Do note that events, unless made static, aren't global. So hooking up to an event in one instance of a class won't cause another instance of that class to "fire" that event. It seems one way to fix your issues would be to make the StandardTasks class take Helper as one of the constructor parameters, so the code would look like this:
Helper helper = new Helper(); // <- you create a helper
helper.OnConsoleUpdate += Processchange; // <- you hook up to the helper class event to actually do something
StandardTasks task = new StandardTasks(helper); //<- you create a task which will use the helper with the hooked up event above

Threading, let one thread know the others progress

Ok, well I have been at it for a while now and I decided to just use threads. I am making a syntax highlighter but I keep getting terrible performance with the file sizes that it will usually be used for. So I made two forms, the first shows the file in plain text and has a button that says "openincolor" when you click that I start a new thread as such
private void button1_Click(object sender, EventArgs e)
{
ColoringThread colorer = new ColoringThread(this.m_bruteView.Text);
Thread theThread = new Thread(new ThreadStart(colorer.OpenColorWindow));
theThread.Start();
}
public class ColoringThread
{
string text;
public ColoringThread(string initText)
{
text = initText;
}
public void OpenColorWindow()
{
Form2 form2 = new Form2(text);
form2.ShowDialog();
}
};
I want this form to send back a message each time it has complete say x lines of coloring. Then I will take that and figure out the progress and display it to the user.
How might I go about sending a message, or event(...? can I do that) to my first form to let it know of the others progress?
One very simple way to do this is with BackgroundWorker. It already provides an event to report progress.
How about something like this? This adds an event to the ColoringThread class which is subscribed to by the calling class.
private void button1_Click(object sender, EventArgs e) {
ColoringThread colorer = new ColoringThread(this.m_bruteView.Text);
colorer.HighlightProgressChanged += UpdateProgress;
Thread theThread = new Thread(new ThreadStart(colorer.OpenColorWindow));
theThread.Start();
}
private void UpdateProgress(int linesComplete) {
// update progress bar here
}
public class ColoringThread
{
string text;
public delegate void HighlightEventHandler(int linesComplete);
public event HighlightEventHandler HighlightProgressChanged;
public ColoringThread(string initText) {
text = initText;
}
public void OpenColorWindow() {
Form2 form2 = new Form2(text);
form2.ShowDialog();
int linesColored = 0;
foreach (String line in text.Split(Environment.NewLine)) {
// colorize line here
// raise event
if (HighlightProgressChanged != null)
HighlightProgressChanged(++linesColored);
}
}
};
You can pass an object as argument to the Thread.Start and share your data between the current thread and the initiating thread.
Here is a good example:
How to share data between different threads In C# using AOP?
Or you can use BackgroundWorker which has ReportProgress
What you need is System.Windows.Threading.Dispatcher's BeginInvoke method. You can't directly modify a WPF object from your background thread, however you can dispatch a delegate to do that.
In your derived Window class object you have the Property Dispatcher, so you use it as follows:
Dispatcher.BeginInvoke(
DispatcherPriority.Normal,
(status) => { StatusTextBox.Text = status },
thestatus
);
I'm sorry that I can't test that currently and I don't have the project here, where I did that. But I'm sure it will work, good luck ;)
Update: Oops, you're using Form's... I've written about WPF, sorry.

How to prevent duplicates, macro or something?

Well, the problem is that I've got a lot of code like this for each event passed to the GUI, how can I shortify this? Macros wont do the work I guess. Is there a more generic way to do something like a 'template' ?
private delegate void DownloadProgressDelegate(object sender, DownloaderProgressArgs e);
void DownloadProgress(object sender, DownloaderProgressArgs e) {
if (this.InvokeRequired) {
this.BeginInvoke(new DownloadProgressDelegate(DownloadProgress), new object[] { sender, e });
return;
}
label2.Text = d.speedOutput.ToString();
}
EDIT:
OK, how can I make this using anonymous delegate in BeginInvoke:
this.BeginInvoke(new DownloadProgressDelegate(DownloadProgress), new object[] { sender, e });
I personally prefer to put the actual action in an Action, then check if this requires an invoke -- this also has the benefit of not needing to declare so many delegates for use with your BeginInvokes. In other words,
void DownloadProgress(object sender, DownloaderProgressArgs e)
{
Action updateLabel = () => label2.Text = d.speedOutput.ToString();
if (this.InvokeRequired)
{
this.BeginInvoke(updateLabel);
}
else
{
updateLabel();
}
}
void DownloadSpeed(object sender, DownloaderProgressArgs e) {
Action updateSpeed = () =>
{
string speed = "";
speed = (e.DownloadSpeed / 1024).ToString() + "kb/s";
label3.Text = speed;
};
if (this.InvokeRequired)
{
this.BeginInvoke(updateSpeed);
}
else
{
updateSpeed();
}
}
This approach lends itself well to use an extension method on Controls that takes an Action and runs it through the check for InvokeRequired.
At a minimum, the extension method should look something like:
public static void MaybeInvoke(this Control c, Action action)
{
if (c.InvokeRequired)
{
this.BeginInvoke(action);
}
else
{
action();
}
}
Annoyingly, the non-generic Action wasn't introduced until .NET 3.5, so you would need to modify things a bit in the examples I gave -- probably using MethodInvoker -- if you're using an earlier version.
You could try T4... but I don't know if it will fit your case well.
One humble thought is to create one routine that handles all your BeginInvoke cases based on a request-type enumerate and using a switch statement. Then at least you only have to check InvokeRequired once. Note that you should probably use if/else rather than return to control the flow.
Well, one way could be to put the generic codes in static class, and access it like, for instance:
Utility.DownloadSpeedUpdate(frm, sender, e);
.net has (in one sense) a rather poor UI framework that actively encourages the problem you have, and the mixing of business logic and UI.
You may be able to make some headway with generics, delegates, and base class/static helper methods.
However, ideally, you need to layer a UI manager on top of .net that helps you out with this properly. This would allow you to separate the UI from the commands that it executes (i.e. you would dynamically bind UI events like keypresses, menu choices, button clicks etc to underlying command objects rather than handling the UI events directly). The UI event handlers would simply look up the command that is bound to the event, then call a centralised "execute Command X" method, and this would handle all the marshalling to the UI thread, etc.
As well as cleaning up this whole mess, this allows you to easily add things like key bindings and scripting/automation to your app, and makes the UI infinitely more scalable and maintainable.
It's no coincidence that this is the core command dispatch approach used in WCF - If you're not using WCF then it's unfortunately up to you to implement an equivalent. It takes a little bit of work to implement a basic command dispatch system, but unless your application is trivial, you'll be glad you did it.
Here's a sample that will save you a bunch of coding if you have many functions requiring InvokeRequired checks. You should notice a few important things:
I use EventHandler<DownloaderProgressArgs> instead of creating new delegates for each function.
The GetInvokeRequiredDelegate function wraps the code that is the same for all of these functions.
This code could be moved into a static class to let you share this among several forms, but that would require more work and a different structure. As it is here, the function just knows which form you're dealing with because the function exists inside that form.
This is all the code that I set up to test GetInvokeRequiredDelegate<T>():
public partial class Form1 : Form
{
public event EventHandler<DownloaderProgressArgs> OnDownloadProgress;
public event EventHandler<DownloaderProgressArgs> OnDownloadSpeed;
public Form1()
{
InitializeComponent();
OnDownloadProgress += GetInvokeRequiredDelegate<DownloaderProgressArgs>(DownloadProgress);
OnDownloadSpeed += GetInvokeRequiredDelegate<DownloaderProgressArgs>(DownloadSpeed);
new System.Threading.Thread(Test).Start();
}
public void Test()
{
OnDownloadProgress(this, new DownloaderProgressArgs() { DownloadSpeed = 1000, speedOutput = 5 });
OnDownloadSpeed(this, new DownloaderProgressArgs() { DownloadSpeed = 2000, speedOutput = 10 });
}
EventHandler<T> GetInvokeRequiredDelegate<T>(Action<object, T> action) where T : EventArgs
{
return ((o, e) =>
{
if (this.InvokeRequired)
{
this.BeginInvoke(action, new object[] { o, e});
} else
{
action(o, e);
}
});
}
void DownloadProgress(object sender, DownloaderProgressArgs d)
{
label2.Text = d.speedOutput.ToString();
}
void DownloadSpeed(object sender, DownloaderProgressArgs e)
{
string speed = "";
speed = (e.DownloadSpeed / 1024).ToString() + "kb/s";
label3.Text = speed;
}
}
public class DownloaderProgressArgs : EventArgs {
public int DownloadSpeed;
public int speedOutput;
}

Example to see return value in multithread scenario

I have a method. I want to return a value not from the main thread but from separate thread. Can you give example of it?
Easiest way is to check out the Background Worker
//set up your BackgroundWorker
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
worker.RunWorkerAsync();
void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Result != null)
{
//process your e.Result
}
}
void worker_DoWork(object sender, DoWorkEventArgs e)
{
//do your work here
e.Result = "testing"; //set the result to any object
}
Your question does not make sense. A method returns a value directly to the method that called it, on the same thread.
EDIT: If you want a method to supply a value to the UI thread on WinForms, you can call the BeginInvoke method. For example,
//In some event handler, such as button1_Click:
ThreadPool.QueueUserWorkItem(delegate {
//This code runs on a background thread.
//In it, you can do something that takes
//a long time without freezing the UI. If
//you need to interact with the UI from
//the background thread, use the Invoke
//method, like this:
var text = (string)Invoke(new Func<string>(() => textBox1.Text));
//I assume you'd want to do something more meaningful.
var result = text + Environment.NewLine + new String(text.Reverse().ToArray());
//To send the result back to the UI thread, call BeginInvoke:
BeginInvoke(new Action(delegate {
//This code is back on the UI thread,
//but it can still use the variables
//defined earlier.
label1.Text = result;
});
});
Jon Skeet has an excellent article on threading within .net in general. However, if you would like a more specific answer to a more specific problem, please post more details.
EDIT:
To make have methods return in a thread other than the main thread, all you need is a second thread. Everything done in that thread will be method calls and returns in that separate thread. Passing data between threads is a much more complex and trick subject. As a starting point, again I point to Jon Skeet's article to get a good base understanding. Beyond that, there are general principles that can be helpful, like Asynchronous calls and BackgroundWorkers (also see here)that can be very helpful, but these are only options, there many ways to do this, and how it should be done is very dependent on the situation.
In order for your method to return something from another thread, that other thread must "have" the something, and must indicate that the "something" is ready to be returned. There is no general case of this, but there are specific cases. For instance, a producer/consumer problem where your other thread produces something and puts it into a queue, and the first thread waits until there's something in the queue, takes it out, then returns it.
Another case that makes a little sense is seen in asynchronous ASP.NET pages. The page starts its life normally, issues one or more asynchronous operations, and then returns back to ASP.NET. It does nothing else until all the asynchronous operations have completed. Then, ASP.NET calls a method in the page that retrieves the results of these operation and uses them in the rest of the page.
You may be able to see that these two cases are very different. That's because you seem to have asked a "learning" question that amounts to "I wonder if a method always has to get its return value from the same thread?" But that's not something you ever have to do in real life, not really.
I will add that the Ada programming language includes something like this - someone who's actually used it will have to say whether it was useful. If I recall correctly, one task can rendezvous with another, and pass data between them.
This does what you asked for:
class DoSomething
{
string result;
public void RunAsync()
{
var t = new BackgroundWorker();
t.DoWork += (sender, e) =>
{
result = string.Empty; // your code goes here instead of string.empty
};
t.RunWorkerCompleted += Finished;//BackgroundWorkerFinished(sender, e);
t.RunWorkerAsync();
}
public void Finished(object sender, RunWorkerCompletedEventArgs e)
{
//result has been set, now what?
}
}
Once you get that down this becomes more useful:
public static void RunAsync(this Action ActionToAsync, Action<object, RunWorkerCompletedEventArgs> FinishedAction)
{
var t = new BackgroundWorker();
t.DoWork += (sender, e) => ActionToAsync();
t.RunWorkerCompleted += (sender, e) => FinishedAction.Invoke(sender,e);//BackgroundWorkerFinished(sender, e);
t.RunWorkerAsync();
}

Categories