By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,501 Members | 2,861 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,501 IT Pros & Developers. It's quick & easy.

How to invoke a delegate from a sub class

P: 25
Hi all
I have a limited understanding of delegates, so bear with me.
In my main Form, I have a listview control.
I also have a class inside the main namespace in which I perform actions on the listview (such as removing a row).
Problem is, the actions the class performs are time consuming, so in order for the Form to avoid freezing, I am executing the class's methods in a separate thread using a 'backGroundWorker'.
Here is where I get stuck. I now can't do anything with the listview because I get this exception:
"Cross-thread operation not valid: Control 'listOfViews' accessed from a thread other than the thread it was created on."
So, I figure that delegates are the answer. I know how to do it in the same class, but I can't figure out how to do it when the actions are performed in a different class.
I would very much appreciate any help !!

Thanks in advance.
Feb 1 '09 #1
Share this Question
Share on Google+
2 Replies


100+
P: 344
Hi,
Delegete is most likely to function pointer, the main difference that it's safe code. Use delegetes to pass methods with a certian signature as a parameter.
Expand|Select|Wrap|Line Numbers
  1. namespace N1
  2. {
  3.     class C
  4.     {
  5.         public delegete void F ( int a1, string a2);
  6.         public static void f1 ( int a, string b)
  7.         { }
  8.         public static void f2 ( int x, string y)
  9.         { }
  10.     }
  11.     class B : C
  12.     {
  13.         public void Any ( F f)
  14.         {
  15.             f ( 1, "h" );
  16.        }
  17.     }
  18.     class D
  19.     {
  20.         B b = new B ( );
  21.         b.Any ( C.f1 );
  22.         b.Any ( C.f2 );
  23.     }
  24. }
  25.  
Only you've to be within the declaration space of both Delegete object and the method you pass it.

Thanks,
Bassem
Feb 1 '09 #2

Expert 100+
P: 190
BackgroundWorker is the correct approach, but you cannot modify the ListView except from the RunWorkerCompleted event. If you modify the ListView inside your background thread, you will receive the cross-thread error.
If you search the forum for BackgroundWorker, you will see several examples and explanations. Here is a recent post with the same issues:
http://bytes.com/topic/c-sharp/answe...-worker-thread
Feb 2 '09 #3

Post your reply

Sign in to post your reply or Sign up for a free account.