C# Delegate with Generic T as Button - c#

I'm losing my mind trying to figure this out. I am developing a large windows application that requires all the controls in the main form to have their values updated in near real time. I moved the processing of this continuous method to its own thread, which in general is fine, but I knew that it required me to create a Delegate for setting my controls that were created in a different thread. However, I have a series of buttons that need to have the same various properties set for each one, but with different values. I was thinking I could setup a Delegate with a Generic type being Button, so I could simply pass in the proper button control when it is time to update its properties. But I am missing something, and it doesn't work:
//If this is wrong, please let me know
private delegate void SafeButtonText<T>(string value) where T : Button;
private void SetButtonTextSafe<T>(string value) where T : Button
{
//Using the generic Button passed in, set its values
if (T.InvokeRequired) //This doesn't compile
{
var d = new SafeButtonText<T>(SetButtonTextSafe<T>);
T.Invoke(d, new object[] { value }); //This doesn't compile
}
else
T.Text = value; //This doesn't compile
}
I thought I could use it like this (which doesn't seem possible)
SetButtonTextSafe<qualityButton>(values[0]);
If this is possible, or if there is a much better way of doing this, please feel free to tell me in detail. (if I can using this on a Button, I'd create another delegate for other control types as well)
Thanks in advance.

A type is just that...a type. You can't invoke an instance of it because you have no instance. It is merely reflected metadata.
You need to pass an instance of your button to your method.
private delegate void SafeButtonText<T>(T button, string value) where T : Button;
private void SetButtonTextSafe<T>(T button, string value) where T : Button
{
//Using the generic Button passed in, set its values
if (button.InvokeRequired) //This now compiles
{
var d = new SafeButtonText<T>(SetButtonTextSafe<T>);
button.Invoke(d, new object[] { value }); //This now compiles
}
else
button.Text = value; //This now compiles
}

Related

Why is the constructor invoked many times?

I am working on silverlight. I created a TextBox and when ever user changed any text in that it should show "*" at the top of file and which should disappear on clicking a save button.
My code works fine for one textbox but when i create second textbox (after the first one) then i found that constructor is invoked two times instead of one. And when i create third textbox(after the two) the constructor is invoked 3 times instead of one. (this textbox is created on a button click in my GUI dynamically which has some text written on it and when i make some change in that text then it shows "*" at top and which disappears on saving it).
Whereas i expect it to be invoked 1 time if i add 1 textbox at a time.
My code to do so is:
private bool modified;
public bool Modified
{
get { return modified; }
set { modified = value; OnPropertyChanged("Modified"); }
}
public ClassConstructor(AnotherClass pv)
{
MessageBox.Show("Number of call check");
setStar(false);
this.isModified = false;
}
private void setStar(bool modified)
{
Tab = this.FileName;
if (modified == false)
{
Tab += "";
}
else
{
Tab += " *";
}
Modified = modified;
}
public void TextChanged(object sender, TextChangedEventArgs e)
{
TextBox tb = (TextBox) sender;
setStar(!TextData.Equals(tb.Text));
}
public void SaveCode(object para)
{
TextData.txt = txt;
setStar(false);
}
Why this constructor is called so many times ? (I mean why my MessageBox for times if i create the fourth textbox) ?
A constructor creates one single instance of that class. So whenever you create a new instance (in your case a new TextBox) the constructor is called to create that object instance. This the sole purpose of constructor - To Be Called when you create an object of that class. Therefore the code inside that constructor is executed. Since you are showing MessageBox inside constructor, you are seeing it 5 times, for 5 new objects and 4 times for 4 new objects. As said in the wiki -
Instance constructors, sometimes referred to as .ctor, are used to
create and initialize any instance member variables when the new
expression is used to create an object of a class.
My first suggestion - Learn what a constructor is because unless you know what a constructor is, you will never understand why this happening. BTW, this is not the error, this is the feature of Object Oriented Programming that whenever you create a new instance, the constructor will be called.
A very good starting point will be here -
Constructor (object-oriented programming)

How do I change the name of an existing event handler?

In Windows Forms, if you change the method name (for example, button1_Click) to something else, it doesn't work any more.
I find this strange because in a console application, as far as I remember, you could name the methods as you wished. I'm trying to understanding what's happening.
How can I change the name of these methods (such as button1_Click)?
This questions is about the case where renaming a method causes the forms designer to stop working. Although I have covered (all that I can think of) how events works in general.
What happened?
What you experience is an artifact of the forms designer.
Sure, you can have any method name you want, the matter is the forms designer is binding those methods to events behind the scenes, if you change the method name after the forms designer has linked it to the event it will no longer work (it can't find the method).
Giving proper names to your event handlers
In Visual Studio, look at the properties of the object you want to bind an event to, and then select events (on the top of the panel):
There you will see a list the available events and you will be able to bind an existing method or type the name for a new one:
If I have already screwed, how do I fix it?
If your designer is not appearing because of this you will have to edit the code file that is generated by the designer. The file generated by the designer has the name of the form followed by .Designer.cs (for example: Form1.Designer.cs), you can find it with your solution explorer:
Note: You may have to expand the sub-tree created on your form to reveal the file.
There you will find a line that looks something like this:
this.button1.Click += new System.EventHandler(this.button1_Click);
And Visual Studio will tell you that button1_Click is not defined. You can edit there the name of the method to the new name, or remove the line to have the designer work again, and bind a new method.
Renaming an existing method without the hassle
You can summon the Rename dialog. This can be done by several ways:
From the Menus: Edit -> Refactor -> Rename
By contextual Menu on the name of the Method: Refactor -> Rename
Put the cursor on the Method name and type Alt + Shift + F10 and then select Rename
Put the cursor on the Method name and press F2
Note: You can customise your Visual Studio, the above menus and keyboard shortcuts may be changed.
The Rename dialog looks like this:
There you can type a new name for the method, and by doing so any reference or call to that method withing the loaded projects will be changed too. That includes the code generated by the Forms Designer.
Binding an event handler by hand
All that the forms designer does is present a UI that facilitates editing the form and write code on your behalf. Don't let it fool you into thinking that you can't write code yourself.
In fact, you can create your own methods and even bind them to the events of your Form. I have been saying "bind" because it is easier to understand at this level, although the accepted lingo is subscribe. So what we are going to do, is create a button and subscribe to its Click event.
First let's take a look at the class of your form, it looks something like this:
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
}
Notice it says partial, that means that there could be more code for this class in another file, in fact that is the file Form1.Designer.cs where the forms designer has been adding code.
Second notice it calls a method InitializeComponent inside the constructor of the form. This method has been created by the forms designer and it takes responsibility of initializing all the controls and components you have added using the forms designer (hence the name of the method).
Now, let's say we want to add a button without the forms designer we can do it like this:
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private Button myButton;
public Form1()
{
InitializeComponent();
// Create a new Button
myButton = new Button();
// Set the properties of the Button
myButton.Location = new System.Drawing.Point(50, 12);
myButton.Size = new System.Drawing.Size(100, 23);
myButton.Text = "My Button";
// Add the Button to the form
this.Controls.Add(myButton);
}
}
}
We have created a private field named myButton of type Button that will hold the new button. Then inside the constructor we add some new lines to create a new Button and assign it to myButton and give it position (Location), Size and Text. And finally we have added the newly created button to the Controls of the form.
Now we want to add an event handler for the Click event on this new button. Remember that this button is not in the forms designer, we we are going to have to do it "by hand".
In order to do so, add the new method (you can named whatever you want):
private void WhenClick(object sender, System.EventArgs e)
{
/* Code */
}
And then add it as an event handler for the Click event of the button (inside the constructor):
// Add an event handler
myButton.Click += new System.EventHandler(WhenClick);
Notice we are not calling WhenClick. instead we are making a reference to it.
Then we are creating a new Delegate of type System.EventHandler that will wrap the reference to the method WhenClick. I suggest to learn about Using Delegates.
I repeat: we are not calling WhenClick. If we were to call WhenClick we would do something like this: WhenClick(param1, param2). Please note that this is not what we are doing here, we haven't added parenthesis (/*...*/) after the method name, so we are not doing a method call.
You can also use some syntactic sugar to make all this easier:
public Form1()
{
InitializeComponent();
// Create a new Button and set its properties
myButton = new Button()
{
Location = new System.Drawing.Point(50, 12),
Size = new System.Drawing.Size(100, 23),
Text = "My Button"
};
// Add the Button to the form
this.Controls.Add(myButton);
// Add an event handler (the compiler infers the delegate type)
myButton.Click += WhenClick;
}
You can even make the event handler an anonymous method:
// Add an event handler (the compiler infers the delegate type)
myButton.Click += (sender, e) =>
{
/* code */
};
What you see here is a C# Lambda expression (more info at MSDN Lambda expressions). Get used to these syntax, because you will see them more and more often.
Understanding events
You have already seen code like this:
button1.Click += button1_Click;
As I told you we are passing a delegate object that has a reference to button1_Click. But that's not all that happens here... we are also giving it to Click.
Let's recapitulate and see how delegates behave. You can think about a delegate like an object that holds a method, or a pointer to a function if you prefer.
To understand this, I'll present some examples you can run as console applications. The first one shows that you can change the method that a delegate points to during runtime:
// Console Application Example #1 ;)
static void Main()
{
Func<int, int> myfunc = null;
myfunc = Add2;
Console.WriteLine(myfunc(7)); // This prints 9
myfunc = MultBy2;
Console.WriteLine(myfunc(7)); // This prints 14
}
static int Add2(int x)
{
// This method adds 2 to its input
return x + 2;
}
static int MultBy2(int x)
{
// This method multiplies its input by 2
return x * 2;
}
Notice myfunc is typed as Func<int, int> this is a generic delegate type that takes an int and returns an int.
Also notice that when I say myfunc = Add2;, it is not calling Add2 (there are no parenthesis there), it is passing a reference of the method itself. the same is true for myfunc = MultBy2;: it is not calling MultBy2, we are passing it.
Using anonymous methods via lambda expressions you can write equivalent code is less lines:
// Console Application Example #1 ;)
static void Main()
{
Func<int, int> myfunc = null;
// This anonymous method adds 2 to its input
myfunc = x => x + 2;
Console.WriteLine(myfunc(7)); // This prints 9
// This anonymous method multiplies its input by 2
myfunc = x => x * 2;
Console.WriteLine(myfunc(7)); // This prints 14
}
Notice that we have two anonymous methods here: x => x + 2 and x => x * 2. The first one (x => x + 2) is equivalent to the method Add2 we had before, and the second one (x => x * 2) is equivalent to the method MultBy2 we had before.
In this example I want you to see that the same delegate can point to different methods along the time. This is accomplished by having a variable that points to the methods!
For the second example, I'll present the "callback" pattern. That is a common pattern in which you pass a delegate as a "callback", that is: something that will be called "back to you" from the code you are calling:
// Console Application Example #2 ;)
static void Main()
{
Func<int, bool> filter = IsPair;
// An array with numbers
var array = new int[]{1, 2, 3, 4, 5, 8, 9, 11, 45, 99};
PrintFiltered(array, filter);
}
static bool IsPair(int x)
{
// True for pair numbers
return x % 2 == 0;
}
static void PrintFiltered(int[] array, Func<int, bool> filter)
{
if (array == null) throw new ArgumentNullException("array");
if (filter== null) throw new ArgumentNullException("filter");
foreach (var item in array)
{
if (filter(item))
{
Console.WriteLine(item);
}
}
}
Outputs:
2
4
8
In this code we are having a variable filter that points to the method IsPair. I'll repeat this again and and again: in the line Func<int, bool> filter = IsPair; we are not calling the method IsPair, instead we are taking a reference to it.
Of course, it is possible to do the same without declaring the filter variable, you can pass the method reference directly:
// Console Application Example #2 ;)
static void Main()
{
// An array with numbers
var array = new int[]{1, 2, 3, 4, 5, 8, 9, 11, 45, 99};
PrintFiltered(array, IsPair); //<---
}
static bool IsPair(int x)
{
// True for pair numbers
return x % 2 == 0;
}
static void PrintFiltered(int[] array, Func<int, bool> filter)
{
if (array == null) throw new ArgumentNullException("array");
if (filter== null) throw new ArgumentNullException("filter");
foreach (var item in array)
{
if (filter(item))
{
Console.WriteLine(item);
}
}
}
I cannot stress this hard enough: When I say PrintFiltered(array, IsPair); it is not calling IsPair, it is passing it as a parameter to PrintFiltered. Here effectively you have a method (PrintFiltered) that can take a reference to another method (IsPair) as a reference.
Of course you can write the same code using an anonymous method that replaces IsPair:
// Console Application Example #2 ;)
static void Main()
{
// An array with numbers
var array = new int[]{1, 2, 3, 4, 5, 8, 9, 11, 45, 99};
PrintFiltered(array, x => x % 2 == 0);
}
static void PrintFiltered(int[] array, Func<int, bool> filter)
{
if (array == null) throw new ArgumentNullException("array");
if (filter== null) throw new ArgumentNullException("filter");
foreach (var item in array)
{
if (filter(item))
{
Console.WriteLine(item);
}
}
}
Outputs:
2
4
8
In this example x => x % 2 == 0 is an anonymous method that is equivalent to the method IsPair we had before.
We have successfully filtered the array to only show the numbers that are pair. You can easily reuse the same code for a different filter. For example, the following line can be used to output only the items in the array that are less than 10:
PrintFiltered(array, x => x < 10);
Outputs:
1
2
3
4
7
8
9
With this example I want to show you that you can take advantage of the delegates to improve the reusability of your code, by having parts that change depending on the delegate you pass.
Now that - hopefully - we understand this, it is not hard to think that you could have a list of Delegate objects, and call them in succession:
// Console Application Example #3 ;)
static void Main()
{
// List<Action<int>> is a List that stores objects of Type Action<int>
// Action<int> is a Delegate that represents methods that
// takes an int but does not return (example: void func(int val){/*code*/})
var myDelegates = new List<Action<int>>();
// We add delegates to the list
myDelegates.Add(x => Console.WriteLine(x));
myDelegates.Add(x => Console.WriteLine(x + 5));
// And we call them in succesion
foreach (var item in myDelegates)
{
item(74);
}
}
Outputs:
74
79
You can see both anonymous methods (x => Console.WriteLine(x) and Console.WriteLine(x + 5)) has been called, one after the other... this happens inside the foreach loop.
Now, we can accomplish similar results with a multicast delegate:
// Console Application Example #3 ;)
static void Main()
{
// This is a delegate... we haven't give it a method to point to:
Action<int> myDelegates = null;
// We add methods to it
myDelegates += x => Console.WriteLine(x);
myDelegates += x => Console.WriteLine(x + 5);
// And we call them in succession
if (myDelegates != null) // Will be null if we don't add methods
{
myDelegates(74);
}
}
Outputs:
74
79
Again, both anonymous methods has been called. And this is exactly how events work. The default implementation of an event uses a multicast delegated wrapped inside. Custom implementation of an event may use a list or similar structure to hold the delegates.
Now, if the event is just a list of delegates... that means the event is keeping a reference to all the methods it wants to call. And it also means that you could remove delegates from the list (or add more than one).
If you want to unsubscribe or unbind from an event, you can do so like this:
this.button1.Click -= button1_Click;
For a delegate object to an anonymous method it is a little bit more complicated, because you will need to keep the delegate in a variable to able to pass it back for removal:
Action<int> myDelegates = null;
// Create the delegate
var myDelegate = x => Console.WriteLine(x);
// Add the delegate
myDelegates += myDelegate;
// ...
// Remove the delegate
myDelegates -= myDelegate;
Did you say custom implementation of an event?
Does that means you can create your own events? Yes, and yes. If you want to publish an event in one of your classes you can declare it just like any other member.
This is an example that uses a multicast delegate:
// Event declaration:
public event EventHandler MyEvent;
// Method to raise the event (aka event dispatcher):
priavet void Raise_MyEvent()
{
var myEvent = MyEvent;
if (myEvent != null)
{
var e = new EventArgs();
myEvent(this, e);
}
}
For a custom implementation take this example:
// List to hold the event handlers:
List<EventHandler> myEventHandlers = new List<EventHandler>();
// Event declaration:
event EventHandler MyEvent
{
add
{
lock (myEventHandlers)
{
myEventHandlers.Add(value);
}
}
remove
{
lock (myEventHandlers)
{
myEventHandlers.Remove(value);
}
}
}
// Method to raise the event (aka event dispatcher):
private void Raise_MyEvent()
{
var e = new EventArgs();
foreach (var item in myEventHandlers)
{
item(this, e);
}
}
Hopefully this not hard to read, now that you know how events work. The only details should be lock, it is there because List is not thread-safe. You could also use a thread-safe data structure or a different locking mechanism, I kept this one for simplicity.
Even if you don't write your own events, there are a few things to learn from here:
Event handlers execute consecutively (by default), so it is good idea that event handlers execute fast (maybe defer to asynchronous operations for the hard work) to prevent "clogging" the event dispatcher.
The event dispatcher usually don't handle exceptions (it can be done), so it is good idea to avoid throwing excepting in event handlers.
The "publisher" of the event is keeping a list of the event handlers, it is a good idea to unsubscribe when you don't need need the event handler anymore.
Notes:
While looking for example I found the series of articles "Delegates in C# - Attempt to Look Inside" by Ed Guzman (Part 1, Part 2, Part 3 and Part 4) very easy to read - although a bit outdated - you should check them out. You may want to read the Evolution of Anonymous Functions in C# for a grasp of what's missing.
Some commonly used Delegate Types built-in in .NET include:
Generic
Action<*> (that is: Action<T>, Action<T1, T2> ...)
Func<*, TResult> (that is: Func<T, TResult>, Func<T1, T2, TResult> ...)
EventHandler<TEventArgs>
Comparison<T>
Converter<TInput, TOutput>
Non Generic
Action
Predicate
EventHandler
ThreadStart
ParametrizedThreadStart
You may be interested in LINQ.
Threading and thread-safety it a even broader topic than delegates and events, don't rush to understand it all.
If you want play along with Lambda Expression and C# in general, I suggest to get a copy of LINQPad. This make reduce the hassle of creating new project to test things.
You can of course change the name of your event. It just sounds like you don't know about the designer file :)
The designer file is just the result of your UI design, and if you don't update the name of your event in the UI it does not compile :)

Temporarily stop form events from either being raised or being handled?

I have a ton on controls on a form, and there is a specific time when I want to stop all of my events from being handled for the time being. Usually I just do something like this if I don't want certain events handled:
private bool myOpRunning = false;
private void OpFunction()
{
myOpRunning = true;
// do stuff
myOpRunning = false;
}
private void someHandler(object sender, EventArgs e)
{
if (myOpRunning) return;
// otherwise, do things
}
But I have A LOT of handlers I need to update. Just curious if .NET has a quicker way than having to update each handler method.
You will have to create your own mechanism to do this. It's not too bad though. Consider adding another layer of abstraction. For example, a simple class called FilteredEventHandler that checks the state of myOpRunning and either calls the real event handler, or suppresses the event. The class would look something like this:
public sealed class FilteredEventHandler
{
private readonly Func<bool> supressEvent;
private readonly EventHandler realEvent;
public FilteredEventHandler(Func<bool> supressEvent, EventHandler eventToRaise)
{
this.supressEvent = supressEvent;
this.realEvent = eventToRaise;
}
//Checks the "supress" flag and either call the real event handler, or skip it
public void FakeEventHandler(object sender, EventArgs e)
{
if (!this.supressEvent())
{
this.realEvent(sender, e);
}
}
}
Then when you hook up the event, do this:
this.Control.WhateverEvent += new FilteredEventHandler(() => myOpRunning, RealEventHandler).FakeEventHandler;
When WhateverEvent gets raised, it will call the FilteredEventHandler.FakeEventHandler method. That method will check the flag and either call, or not call the real event handler. This is pretty much logically the same as what you're already doing, but the code that checks the myOpRunning flag is in only one place instead of sprinkled all over your code.
Edit to answer question in the comments:
Now, this example is a bit incomplete. It's a little difficult to unsubscribe from the event completely because you lose the reference to the FilteredEventHandler that's hooked up. For example, you can't do:
this.Control.WhateverEvent += new FilteredEventHandler(() => myOpRunning, RealEventHandler).FakeEventHandler;
//Some other stuff. . .
this.Control.WhateverEvent -= new FilteredEventHandler(() => myOpRunning, RealEventHandler).FakeEventHandler; //Not gonna work!
because you're hooking up one delegate and unhooking a completely different one! Granted, both delegates are the FakeEventHandler method, but that's an instance method and they belong to two completely different FilteredEventHandler objects.
Somehow, you need to get a reference to the first FilteredEventHandler that you constructed in order to unhook. Something like this would work, but it involves keeping track of a bunch of FilteredEventHandler objects which is probably no better than the original problem you're trying to solve:
FilteredEventHandler filter1 = new FilteredEventHandler(() => myOpRunning, RealEventHandler);
this.Control.WhateverEvent += filter1.FakeEventHandler;
//Code that does other stuff. . .
this.Control.WhateverEvent -= filter1.FakeEventHandler;
What I would do, in this case, is to have the FilteredEventHandler.FakeEventHandler method pass its 'this' reference to the RealEventHandler. This involves changing the signature of the RealEventHandler to either take another parameter:
public void RealEventHandler(object sender, EventArgs e, FilteredEventHandler filter);
or changing it to take an EventArgs subclass that you create that holds a reference to the FilteredEventHandler. This is the better way to do it
public void RealEventHandler(object sender, FilteredEventArgs e);
//Also change the signature of the FilteredEventHandler constructor:
public FilteredEventHandler(Func<bool> supressEvent, EventHandler<FilteredEventArgs> eventToRaise)
{
//. . .
}
//Finally, change the FakeEventHandler method to call the real event and pass a reference to itself
this.realEvent(sender, new FilteredEventArgs(e, this)); //Pass the original event args + a reference to this specific FilteredEventHandler
Now the RealEventHandler that gets called can unsubscribe itself because it has a reference to the correct FilteredEventHandler object that got passed in to its parameters.
My final advice, though is to not do any of this! Neolisk nailed it in the comments. Doing something complicated like this is a sign that there's a problem with the design. It will be difficult for anybody who needs to maintain this code in the future (even you, suprisingly!) to figure out the non-standard plumbing involved.
Usually when you're subscribing to events, you do it once and forget it - especially in a GUI program.
You can do it with reflection ...
public static void UnregisterAllEvents(object objectWithEvents)
{
Type theType = objectWithEvents.GetType();
//Even though the events are public, the FieldInfo associated with them is private
foreach (System.Reflection.FieldInfo field in theType.GetFields(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance))
{
//eventInfo will be null if this is a normal field and not an event.
System.Reflection.EventInfo eventInfo = theType.GetEvent(field.Name);
if (eventInfo != null)
{
MulticastDelegate multicastDelegate = field.GetValue(objectWithEvents) as MulticastDelegate;
if (multicastDelegate != null)
{
foreach (Delegate _delegate in multicastDelegate.GetInvocationList())
{
eventInfo.RemoveEventHandler(objectWithEvents, _delegate);
}
}
}
}
}
You could just disable the container where all these controls are put in. For example, if you put them in a GroupBox or Panel simply use: groupbox.Enabled = false; or panel.Enabled = false;. You could also disable the form From1.Enabled = false; and show a wait cursor. You can still copy and paste these controls in a container other than the form.

Show text on a label for a specific time

I want to show a text in a label for a particular time so I did a search on google and I found these two solutions :
The first solution is :
public void InfoLabel(string value)
{
if (InvokeRequired)
{
this.Invoke(new Action<string>(InfoLabel), new object[] { value });
return;
}
barStaticItem3.Caption = value;
if (!String.IsNullOrEmpty(value))
{
System.Timers.Timer timer =
new System.Timers.Timer(3000) { Enabled = true };
timer.Elapsed += (sender, args) =>
{
this.InfoLabel(string.Empty);
timer.Dispose();
};
}
}
The second solution :
private void ShowTextForParticularTime(String caption)
{
Timer t = new Timer { Interval = 5000, Enabled = true};
t.Tick += (sender, args) => OnTimerEvent(sender, args, caption);
}
private void OnTimerEvent(object sender, EventArgs e, String caption)
{
barStaticItem3.Caption = caption;
}
Could you please tell me the deffrence between the two solutions, and why we use this symbole "=>" , also I understood nothing from this line :
if (InvokeRequired)
{
this.Invoke(new Action<string>(InfoLabel), new object[] { value });
return;
}
Okay, there is a good amount to explain here.
There is no major differences between the two options you have shown. The reason they look different is because the first id declaring a delegate method (lambda expression) inside the public method, while the second is just creating an event handler. They do almost the exact same thing. Infact you can see that in the delegate method you have the tradition event handler prameters (object sender, EventArgs e). Personally I prefer the second solution because it looks cleaner to me.
Invoke Required is used to handle threading. In C# errors will be thrown if a thread that didn't create a visual object tries to alter the visual object. To get around this we make a call to the thread that created the visual object by calling "Invoke". The "InvokeRequired" property just tells us if the current thread did not create the visual object. You should always use this when you are threading or making delegate methods (because you can't control the thread that runs them.)
I hope this brief explanation helps. Comment if it is unclear
In WinForms and WPF, the UI can only be updated from the thread that created the control in question. These two approach show two ways to update your UI from a different thread.
The first approach manually checks if the code is running on a different thread and, if it is, marshals the call to the UI thread.
The second approach uses an event, leaving the details of marshaling to .NET
The symbol => represents a lamda expression. You can think of it much like a function pointer (though sometimes it is really something called an expression tree behind the scenes). Essentially, it creates a variable that points to code that can be called by referencing that variable.
Either approach should work fine. Personally I prefer the second approach because it allows the framework to handle more of the plumbing work.

Generic Types: There is no implicit reference conversion from ToolStripStatusLabel to Control

I'm wanting to update the UI from a SerialPort DataReceived event handler. I discovered a problem because the event handler was implicitly running in a different thread to the form, so rather than simply update the UI...
myLabel.Text = "Some text";
...I had to take the following approach:
InvokeControlAction<Label>(myLabel, lbl=> lbl.Text= "Some text");
...
public static void InvokeControlAction<t>(t cont, Action<t> action) where t : Control
{
if (cont.InvokeRequired)
{
cont.Invoke(new Action<t, Action<t>>(InvokeControlAction),
new object[] { cont, action });
}
else
{
action(cont);
}
}
So far so good... However, now I want to update a ToolStripStatusLabel - using the same approach yields a 'there is no implicit reference conversion between ToolStripStatusLabel and Forms.Control' error.
From what I have read, the problems stems from the fact that you can't Invoke a ToolStripStatusLabel.
So how best do I handle this?
Note: delegates, etc are at the threshold of my current ability, so an explanation alongside a solution would be appreciated.
UPDATE 1: Just to clarify, I tried to create ToolStripStatusLabel equivalent of InvokeControlAction, but this won't work because it doesn't have an invoke method.
RESULT: After revisiting my solution, I've implemented it as an Extension Method as Jimmy originally suggested.
I created an static ExtensionMethod class (in it's own 'ExtensionMethods' namespace), added in the InvokeOnToolStripItem method, add a 'using ExtensionMethods;' directive in my original class and called the methods as follows:
tsStatusValue.InvokeOnToolStripItem(ts => ts.Text = "ALARM signal received");
ToolStripStatusLabel does not inherit from Control, and that's why your generic constraint fails for the exact reason you posted.
What is more, ToolStripStatusLabel (or any ToolStripItem in fact) doesn't have Invoke method. Luckily, containing ToolStrip has, which can be easily accessed using GetCurrentParent method.
Here's extension method that works on any ToolStripItem:
public static void InvokeOnToolStripItem<T>(this T item, Action<T> action)
where T : ToolStripItem
{
ToolStrip parent = item.GetCurrentParent();
if (parent.InvokeRequired)
{
parent.Invoke((Delegate)action, new object[] { item });
}
else
{
action(item);
}
}
You can use it by simply calling:
myToolStripLabel.InvokeOnToolStripItem(label => label.Text = "Updated!");
myToolStripProgressBar.InvokeOnToolStripItem(bar => bar.PerformStep());
To explain the error message, you have writen
where t : Control
but ToolStripStatusLabel does not inherit from Control.
Not sure if that helps you at all and don't really have a solution yet :(

Categories