Invoke and BeginInvoke

前端 未结 5 1762
盖世英雄少女心
盖世英雄少女心 2020-12-29 06:30

Greetings, I am developing some application in C#. At the moment I\'m dealing with threading and I have a question that I have in my mind. What is the difference between In

5条回答
  •  悲哀的现实
    2020-12-29 07:26

    Control.BeginInvoke doesn't work on a different thread (or threadpool), a delegate.BeginInvoke does. MSDN's one liner says:

    Executes the specified delegate asynchronously on the thread that the control's underlying handle was created on.

    However Control.BeginInvoke simply uses PostMessage and returns - no CLR Thread is created.

    The PostMessage function places (posts) a message in the message queue associated with the thread that created the specified window and returns without waiting for the thread to process the message.

    This article summarises whether to use Invoke or BeginInvoke quite well:

    Which function to use, you ask. It really depends on your requirement. If you want your UI update to complete before proceeding, you use Invoke. If there is no such requirement, I'd suggest using BeginInvoke, as it makes the thread calling it seemingly "faster". There are a few gotcha's with BeginInvoke though.

    • If the function you are calling via BeginInvoke accesses shared state (state shared between the UI thread and other threads), you are in trouble. The state might change between the time you called BeginInvoke and when the wrapped function actually executes, leading to hard to find timing problems.
    • If you are passing reference parameters to the function called via BeginInvoke, then you must make sure that no one else modifies the passed object before the function completes. Usually, people clone the object before passing it to BeginInvoke, which avoids the problem altogether.

提交回复
热议问题