none
Need help in implementing an attribute to do the UI thread marshaling RRS feed

  • Question

  • Hi

    I want to create code like this 

     private void MainForm_Load(object sender, EventArgs e)
            {
                Thread t1 = new Thread(new ThreadStart(Run));
                t1.Start();

            }

            [RunInUIContext]
            // helps marshaling across UI thread
            public void Run()
            {
                this.Controls.Add(new Button());
            }

    Is this possible if yes , what would be the approach??

    Tuesday, December 23, 2008 10:16 AM

Answers

  • Technically it is possible, practically it is not.  Every method call would have to be made late-bound through MethodInfo so you can use its GetCustomAttribute() method to check if the attribute is there.  The arguments for that method call are a significant problem.  Not only do you need to whack them into object[] form, you'll also need to dynamically create delegate types that are compatible with the method signature.

    You'll end up with a mass of code that is very hard to use and incredibly slow.  Much worse than doing it the traditional way, which is merely awkward and verbose.

    Hans Passant.
    • Marked as answer by Zhi-Xin Ye Monday, December 29, 2008 12:41 PM
    Tuesday, December 23, 2008 11:02 AM
    Moderator

All replies

  • Technically it is possible, practically it is not.  Every method call would have to be made late-bound through MethodInfo so you can use its GetCustomAttribute() method to check if the attribute is there.  The arguments for that method call are a significant problem.  Not only do you need to whack them into object[] form, you'll also need to dynamically create delegate types that are compatible with the method signature.

    You'll end up with a mass of code that is very hard to use and incredibly slow.  Much worse than doing it the traditional way, which is merely awkward and verbose.

    Hans Passant.
    • Marked as answer by Zhi-Xin Ye Monday, December 29, 2008 12:41 PM
    Tuesday, December 23, 2008 11:02 AM
    Moderator
  • Ok , even for parameterless functions we will need to intercept code ,

    I know two approaches for that but both involve deriving from ContextBoundObject or MarshalByRefObject , is there any other way?
    Tuesday, December 23, 2008 11:08 AM