Archive for the Category 'C'

Invoke

Sooner or later you will develop an application that makes use of threads to perform background tasks.
Maybe if you have never used the Threads, I recommend this article (in English) An Introduction to Programming with C # Threads

Dell'Invoke The problem occurs when you try to update the UI from a thread of a Form. In fact. NET allows the invocation of the function object System.Windows.Forms.Control only by the thread in which the object was created. To overcome this obstacle we need to use the functions Control.Invoke (synchronous call) or Control.BeginInvoke (asynchronous call). Normally, our approach would be to write as many delegates as there are objects to be invoked or methods to be updated:
delegate void AggiungiListboxDelegate(string msg);
[...]
if (this.InvokeRequired) {
Invoke(new AggiungiListboxDelegate(AggiungiAListBox), new object[] { itm } );
}
else
{
AggiungiAListBox(itm);
}

However, there is an easier method and used in a generic way in most cases. We write the generic delegates receive:

  • or object, the name of the property to be valued and the new value to be assigned
  • or object, the method name and parameters to pass to invoke the method

delegate void SetPropertyDelegate(object ctl, string objName, object newValue);
delegate void SetMethodDelegate(object obj, string methodName, object[] parameters);
[...]

void SetProperty(object ctl, string propName, object newValue) {
Type t = ctl.GetType();
PropertyInfo pi = t.GetProperty(propName);

if (pi! = null) {
pi.SetValue (ctl, newValue, null);
}
}
SetMethod void (object ctl, String methodName, Object [] parameters) {
Type t = ctl.GetType ();
MethodInfo mi = t.GetMethod (methodName);

if (mi! = null) {
mi.Invoke (ctl, parameters);
}
}
An example of use:

Invoke(new SetPropertyDelegate(SetProperty), new object[] { (object)lblErrMessage, "Text", errmsg });

oppure

Invoke(new SetMethodDelegate(SetMethod), new object[] { (object)this, "Close", (new object[] {}) } );

To you, the burden of improving the idea :)

[Slashdot] [Digg] [Reddit] [Del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Tags: Call Center Systems | VoIP PBX | Asterisk Consultant Naples | PBX Phone | VoIP | Asterisk CTI | PBX | IP Phones | Networking | Linux


Development of IVR systems, call center, VoIP PBX.