How to invoke a delegate from a sub class

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • nsteiner
    New Member
    • Dec 2008
    • 25

    How to invoke a delegate from a sub class

    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 'backGroundWork er'.
    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.
  • Bassem
    Contributor
    • Dec 2008
    • 344

    #2
    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.
    Code:
    namespace N1
    {
        class C
        {
            public delegete void F ( int a1, string a2);
            public static void f1 ( int a, string b)
            { }
            public static void f2 ( int x, string y)
            { }
        }
        class B : C
        {
            public void Any ( F f)
            {
                f ( 1, "h" );
           }
        }
        class D
        {
            B b = new B ( );
            b.Any ( C.f1 );
            b.Any ( C.f2 );
        }
    }
    Only you've to be within the declaration space of both Delegete object and the method you pass it.

    Thanks,
    Bassem

    Comment

    • mldisibio
      Recognized Expert New Member
      • Sep 2008
      • 191

      #3
      BackgroundWorke r is the correct approach, but you cannot modify the ListView except from the RunWorkerComple ted event. If you modify the ListView inside your background thread, you will receive the cross-thread error.
      If you search the forum for BackgroundWorke r, you will see several examples and explanations. Here is a recent post with the same issues:

      Comment

      Working...