Re: Please suggest a Generic Cross-Thread Safe Invocation technique

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Peter Duniho

    Re: Please suggest a Generic Cross-Thread Safe Invocation technique

    On Thu, 26 Jun 2008 00:05:42 -0700, <zorrothefox.gr oups@gmail.comw rote:
    [...]
    However, the above technique seems to be a bit klunky (IMO).
    Yes, it is "klunky". IMHO, it's unfortunate that that's the model MSDN
    continues to suggest everywhere.
    Is there
    no way that this could be automated such that for each control's
    function, I need not add a delegate? Since there are quite a few
    controls that I need to access in the background thread (at least for
    read purpose), the number of delegates and functions seem to be
    excessive.
    If you are using .NET 3.0 or later, Microsoft has introduced the "Action"
    generic delegate types. There are a variety of them, handling zero up to
    (I think) four parameters. In your example, rather than declaring a
    specific delegate type, you'd just use "Action<ListVie w>" as the type.

    However, IMHO it's better to avoid the whole MSDN-suggested approach
    altogether, and use anonymous methods that are invoked unconditionally .
    So instead of the mess you posted before, you'd have something like this:

    public void ListClear(ListV iew list)
    {
    Invoke((MethodI nvoker)delegate { list.Clear(); });
    }

    You could use the no-parameter "Action" delegate type instead if you like.

    In practically all the examples I've run into, the method is always
    initially being called from the wrong thread anyway, and so InvokeRequired
    is always true the first time into the method anyway. But even when
    that's not the case, there's no harm in just calling Invoke() directly.
    It probably costs a little more performance-wise, but I suspect that in
    most cases that performance difference is inconsequential (and you at
    least get out of the check for InvokeRequired, which offsets at least a
    little bit of the performance hit :) ).
    After all, at least logically, each control knows already which thread
    it belongs to. Could it not be arranged in such a way that we add some
    code to the form such that whenever a control is accessed, the form
    automatically checks for the thread accessing the control, and passes
    the same request onto the proper thread?
    Sure. Microsoft could have simply done so in the situations where they
    now throw the exception. Presumably they had some specific reason for not
    doing so though. Perhaps the check for InvokeRequired is costly, for
    example, and they didn't want the general case to suffer
    performance-wise. I don't know. But the fact is, they didn't. I'm
    satisfied just with simplifying the code as I've shown above. Works fine
    for me. :)

    Pete
Working...