Различие между BeginInvoke и потоком. Запустить

Я использовал http://www.rubular.com/ несколько раз, кажется, делает задание.

20
задан Serhat Ozgel 4 August 2009 в 09:25
поделиться

6 ответов

BeginInvoke will post the action in the message queue of the message pump on the same thread as the Form, it will not create a new thread.

Control.BeginInvoke behaves similar to an asynchronous thread start, but has important internal differences.

Read in further detail an article here.

17
ответ дан 30 November 2019 в 00:27
поделиться

BeginInvokes executes the delegate asynchronously on the UI thread (which is why it hangs the UI), by posting a message to the window. That's what you need to do if the code in the delegate accesses the UI.

The approach with Thread.Start executes the delegates on a new, independant thread.

8
ответ дан 30 November 2019 в 00:27
поделиться

Thread.Start runs it on your new Thread.

Control.BeginInvoke runs the method on the thread that the Control this belongs to. If you are currently on the thread of the control, the method is not run until you return control to the message loop, e.g. exit your event handler.

3
ответ дан 30 November 2019 в 00:27
поделиться

Как уже писали другие, Thread .Start запустит новый поток, а Control.BeginInvoke () запустит код в потоке пользовательского интерфейса (необходимо, например, если вы хотите изменить значение поля).

Однако я обнаружил, что самый простой способ выполнения фоновая задача в WinForms - использовать BackgroundWorker . Вы перетаскиваете его в форму, подключаете события и вызываете RunWorkerAsync (). Затем вы записываете свою фоновую задачу в событие DoWork. Любое обновление пользовательского интерфейса может быть помещено в событие RunWorkerCompleted.

Использование BackgroundWorker позволяет избежать всей раздражающей обработки потоков и вещей IsInvokeRequired.

Вот более подробная практическая статья .

1
ответ дан 30 November 2019 в 00:27
поделиться

Попробуйте это.

class Form1: Form
{
   public void ButtonWasClicked(object sender, EventArgs e)
   {
       /* Call the UI's Invoke() method */
       this.Invoke((MethodInvoker)delegate()
       {
           /* Stuff to do.. you can access UI elements too without
            * the nasty "Control accessed from another thread.."
            * Use BeginInvoke() only if you have code after this section
            * that you want the UI to execute without waiting for this 
            * inner blockto finish. 
            */
       });
   }
}

Что касается BeginInvoke (), он используется, поэтому функция вернется немедленно, и будет выполнена следующая строка и так далее, и так далее, не дожидаясь завершения метода .

Разница в том, что если вы создадите поток, у вас будет больше контроля над ним, как и над любым другим потоком. Вы столкнетесь с CrossThreadExceptions! В то время как если вы используете IAsyncResult и BeginInvoke (), у вас не будет контроля над потоком выполнения асинхронной операции, поскольку он управляется средой выполнения.

С помощью вызова вы также можете отправить больше параметров в метод и иметь вызываемый метод после завершения операции.

MyDelegateWithTwoParam del = new MyDelegateWithTwoParam(_method);
AsyncCallback callback = new AsyncCallback(_callbackMethod);
IAsyncResult res = del.BeginInvoke(param1, param2, callback, null);

private void _callbackMethod(IAsyncResult iar) {
   /* In this method you can collect data that your operation might have returned.
    * If MyDelegateWithTwoParam has a return type, you can find out here what i was. */
}

Я широко использовал и то, и другое для разработки пользовательского интерфейса. Я бы больше использовал потоки для сервис-подобных объектов. Не волнуйтесь, если первый подход требует дополнительной секунды для запуска: Thread.Abort () не всегда лучшее решение. Попробуйте _abort flags в вашем коде процесса и заблокируйте его.

Надеюсь, я ответил на вопрос.

Лео Бруццанити

3
ответ дан 30 November 2019 в 00:27
поделиться

the difference would be that the BeginInvoke method simply calls the delegate asynchronously on the SAME thread.

Using the Thread.Start, you'll be creating an entirely different thread.

Thread.Start will definately give you better performance!

0
ответ дан 30 November 2019 в 00:27
поделиться
Другие вопросы по тегам:

Похожие вопросы: