Ошибка невозможно вызвать invoke или begininvoke

Корпорация Майкрософт распространяет исправления Microsoft SQL Server 2008 как один загружаемый файл. Так как исправления являются накопительными, каждый выпуск содержит все исправления и все исправления безопасности, которые были включены в предыдущие 2008 SQL Server исправления выпуска.

Симптомы

В Windows 7 выполните одно из следующих действий:

  • Установка Microsoft SQL Server 2008 через графический интерфейс пользователя (GUI).

  • Обновления SQL Server 2000 или SQL Server 2005 до SQL Server 2008 через графический Интерфейс.

  • Установите кластер SQL Server 2008 через графический Интерфейс.

  • Обновление из кластера SQL Server 2000 или SQL Server 2005 кластера для кластера SQL Server 2008 через графический Интерфейс.

После выполнения этих операций на этапе Настройки правила поддержки установки может появиться следующее сообщение об ошибке:

Invoke или BeginInvoke не может вызываться для элемента управления, пока не будет создан дескриптор окна.

Кроме того в одном из файлов журнала установки программы установки SQL Server может регистрироваться следующее сообщение об ошибке. Например в файле Detail_LandingPage.txt может регистрироваться следующее сообщение об ошибке:

< Дата >< время > Slp: тип исключения: System.InvalidOperationException
< Дата >< время > предустановки блокированной системы: сообщение:

< Дата >< время > Slp: Invoke или BeginInvoke не может вызываться для элемента управления, пока не будет создан дескриптор окна.
< Дата >< время > Slp: стека:

< Дата >< время > предустановки блокированной системы: в System.Windows.Forms.Control.WaitForWaitHandle (WaitHandle waitHandle)

< Дата >< время > предустановки блокированной системы: в System.Windows.Forms.Control.MarshaledInvoke (вызывающий объект элемента управления, метод делегата, объект args [], Boolean синхронный)

< Дата >< время > предустановки блокированной системы: в System.Windows.Forms.Control.Invoke (метод делегата, объект args [])

< Дата >< время > предустановки блокированной системы: в Microsoft.SqlServer.Configuration.UIExtension.WaitScreen.Close()

< Дата >< время > предустановки блокированной системы: в Microsoft.SqlServer.Configuration.UIExtension.UserInterfaceService.Start (Строка моникера)

< Дата >< время > предустановки блокированной системы: в Microsoft.SqlServer.Configuration.UIExtension.StartAction.ExecuteAction (строка actionId)
< Дата >< время > предустановки блокированной системы: в Microsoft.SqlServer.Chainer.Infrastructure.Action.Execute (строка actionId, TextWriter errorStream)

< Дата >< время > предустановки блокированной системы: в Microsoft.SqlServer.Setup.Chainer.Workflow.ActionInvocation.InvokeAction (WorkflowObject метабазы, TextWriter statusStream)

< Дата >< время > предустановки блокированной системы: в Microsoft.SqlServer.Setup.Chainer.Workflow.PendingActions.InvokeActions (WorkflowObject metaDb, TextWriter loggingStream)

< Дата >< время > Slp: правило выполняется оценка: успешно

Решение

Пакет обновления 1 для SQL Server 2008


Исправление этой уязвимости первого выпуска в накопительное обновление 4 для SQL Server 2008 Пакет обновления 1. Дополнительные сведения о этот накопительный пакет обновления щелкните следующий номер статьи базы знаний Майкрософт:

973602 накопительного обновления 4 для SQL Server 2008 Пакет обновления 1Примечание. Поскольку построения являются накопительными, каждый новый выпуск исправление содержит все исправления и все исправления, входившие в состав предыдущих SQL Server 2008 выпуска исправлений. Корпорация Майкрософт рекомендует учесть применение последний выпуск исправления, содержащего это исправление. Для получения дополнительных сведений щелкните следующий номер статьи базы знаний Майкрософт:

970365 SQL Server 2008 выполняет построение, выпущенных после выпуска SQL Server 2008 Пакет обновления 1
Исправления Microsoft SQL Server 2008 создаются для определенных пакетов обновления SQL Server. Необходимо установить исправление SQL Server 2008 Пакет обновления 1 для установки SQL Server 2008 Пакет обновления 1. По умолчанию какие-либо исправления, включенный в пакет обновления SQL Server включено в следующий пакет обновления SQL Server.

В версии SQL Server 2008

Важно. Если на компьютере с официальной версией SQL Server 2008 необходимо установить это исправление.

Исправление этой уязвимости первого выпуска накопительного обновления 8. Дополнительные сведения о том, как получить этот накопительный пакет обновления для SQL Server 2008, щелкните следующий номер статьи базы знаний Майкрософт:

975976 накопительного обновления 8 для SQL Server 2008Примечание. Поскольку построения являются накопительными, каждый новый выпуск исправление содержит все исправления и все исправления, входившие в состав предыдущих SQL Server 2008 выпуска исправлений. Мы рекомендуем рассмотреть применение последнего выпуска исправления, содержащего это исправление. Для получения дополнительных сведений щелкните следующий номер статьи базы знаний Майкрософт:

956909 SQL Server 2008 выполняет построение, выпущенных после выпуска SQL Server 2008

Статус

Корпорация Майкрософт подтверждает, что это проблема продуктов Майкрософт, перечисленных в разделе «Относится к».

Ссылки

Дополнительные сведения о добавочных модель обслуживания для SQL Server щелкните следующий номер статьи базы знаний Майкрософт:

935897 добавочных модель обслуживания доступна из группы SQL Server для предоставления исправления для проблем, о которых сообщалось в

Дополнительные сведения о схеме именования для обновления SQL Server щелкните следующий номер статьи базы знаний Майкрософт:

Новая схема присвоения имен 822499 для программного обеспечения Microsoft SQL Server пакетами обновления

Для получения дополнительных сведений о терминологии обновлений программного обеспечения щелкните следующий номер статьи базы знаний Майкрософт:

Описание 824684 Стандартные термины, используемые при описании обновлений программных продуктов Майкрософт

Нужна дополнительная помощь?

Нужны дополнительные параметры?

Изучите преимущества подписки, просмотрите учебные курсы, узнайте, как защитить свое устройство и т. д.

В сообществах можно задавать вопросы и отвечать на них, отправлять отзывы и консультироваться с экспертами разных профилей.

It’s possible that you’re creating your controls on the wrong thread. Consider the following documentation from MSDN:

This means that InvokeRequired can
return false if Invoke is not required
(the call occurs on the same thread),
or if the control was created on a
different thread but the control’s
handle has not yet been created.

In the case where the control’s handle
has not yet been created, you should
not simply call properties, methods,
or events on the control. This might
cause the control’s handle to be
created on the background thread,
isolating the control on a thread
without a message pump and making the
application unstable.

You can protect against this case by
also checking the value of
IsHandleCreated when InvokeRequired
returns false on a background thread.
If the control handle has not yet been
created, you must wait until it has
been created before calling Invoke or
BeginInvoke. Typically, this happens
only if a background thread is created
in the constructor of the primary form
for the application (as in
Application.Run(new MainForm()),
before the form has been shown or
Application.Run has been called.

Let’s see what this means for you. (This would be easier to reason about if we saw your implementation of SafeInvoke also)

Assuming your implementation is identical to the referenced one with the exception of the check against IsHandleCreated, let’s follow the logic:

public static void SafeInvoke(this Control uiElement, Action updater, bool forceSynchronous)
{
    if (uiElement == null)
    {
        throw new ArgumentNullException("uiElement");
    }

    if (uiElement.InvokeRequired)
    {
        if (forceSynchronous)
        {
            uiElement.Invoke((Action)delegate { SafeInvoke(uiElement, updater, forceSynchronous); });
        }
        else
        {
            uiElement.BeginInvoke((Action)delegate { SafeInvoke(uiElement, updater, forceSynchronous); });
        }
    }
    else
    {    
        if (uiElement.IsDisposed)
        {
            throw new ObjectDisposedException("Control is already disposed.");
        }

        updater();
    }
}

Consider the case where we’re calling SafeInvoke from the non-gui thread for a control whose handle has not been created.

uiElement is not null, so we check uiElement.InvokeRequired. Per the MSDN docs (bolded) InvokeRequired will return false because, even though it was created on a different thread, the handle hasn’t been created! This sends us to the else condition where we check IsDisposed or immediately proceed to call the submitted action… from the background thread!

At this point, all bets are off re: that control because its handle has been created on a thread that doesn’t have a message pump for it, as mentioned in the second paragraph. Perhaps this is the case you’re encountering?

The difference between Invoke and BeginInvoke is that the former is synchronous (waits for completion) while the later is asynchronous (sort of fire-and-forget). However, both work by posting a message to the UI message loop which will cause the delegate to be executed when it gets to that message.

The InvokeRequired property determines whether you need to Invoke at all or if it is already on the correct thread, not whether you want synchronous or asynchronous calling. If InvokeRequired is false you are (in theory) already running on the UI thread and can simply perform synchronous actions directly (or still BeginInvoke if you need to fire them off asynchronously). This also means you can’t use Invoke if InvokeRequired is false, because there’s no way for the message loop on the current thread to continue. So that’s one big problem with your code above, but not necessarily the error you’re reporting. You can actually use BeginInvoke in either case, if you watch out for recursive invocation, and so on.

However, you can’t use either one without a window handle. If the Form/Control has been instantiated but not initialized (ie. before it is first shown) it may not have a handle yet. And the handle gets cleared by Dispose(), such as after the Form is closed. In either case InvokeRequired will return false because it is not possible to invoke without a handle. You can check IsDisposed, and there is also a property IsHandleCreated which more specifically tests if the handle exists. Usually, if IsDisposed is true (or if IsHandleCreated is false) you want to punt into a special case such as simply dropping the action as not applicable.

So, the code you want is probably more like:

if (IsHandleCreated)
{
    // Always asynchronous, even on the UI thread already.  (Don't let it loop back here!)
    BeginInvoke(new UpdateTextFieldDelegate(WriteToForm), finished, numCount);
    return; // Fired-off asynchronously; let the current thread continue.

    // WriteToForm will be called on the UI thread at some point in the near future.
}
else
{
    // Handle the error case, or do nothing.
}

Or maybe:

if (IsHandleCreated)
{
    // Always synchronous.  (But you must watch out for cross-threading deadlocks!)
    if (InvokeRequired)
        Invoke(new UpdateTextFieldDelegate(WriteToForm), finished, numCount);
    else
        WriteToForm(finished, numCount); // Call the method (or delegate) directly.

    // Execution continues from here only once WriteToForm has completed and returned.
}
else
{
    // Handle the error case, or do nothing.
}

R@Z()r

10 / 12 / 2

Регистрация: 13.01.2010

Сообщений: 363

1

.NET 4.x

25.12.2010, 18:20. Показов 34457. Ответов 5

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Помогите исправить ошибку

C#
1
Invoke(new MethodInvoker(InvokedConnectionStateChange)); // Ошибка: Невозможно вызвать Invoke или BeginInvoke для элемента управления до завершения создания дескриптора окна.

архив с проектом прикреплен

Вложения

Тип файла: rar Project.rar (134.6 Кб, 156 просмотров)



0



Mikant

1318 / 991 / 127

Регистрация: 08.12.2009

Сообщений: 1,299

25.12.2010, 21:38

2

запустить твой проект не удалось: connetion is not active. но попробуй все-таки написать так (по-людски)

C#
1
2
3
if (this.InvokeRequired)
    this.Invoke(new MethodInvoker(InvokedConnectionStateChange));
else InvokedConnectionStateChange();

Добавлено через 2 часа 45 минут
я тут код почитал пару минут. самому не стыдно, разор?



0



Почетный модератор

Эксперт .NET

8715 / 3667 / 404

Регистрация: 14.06.2010

Сообщений: 4,513

Записей в блоге: 9

25.12.2010, 21:39

3

Не по теме:

Цитата
Сообщение от Mikant
Посмотреть сообщение

Добавлено через 2 часа 45 минут
я тут код почитал пару минут.

:rofl:

А вообще ошибка из-за того что окно не успевает создаться, т.е. метод CreateHandle ещё не был вызван. Советую перед тем как выполнять Invoke из другого потока и при этом нет точной уверенности что форма уже создана проверять IsHandleCreated.



2



Konctantin

969 / 772 / 171

Регистрация: 12.04.2009

Сообщений: 1,700

25.12.2010, 22:20

4

не слабо, вы слышали что такое форматная строка?

C#
1
2
3
4
static void Log(string text)
        {
            log += "n" + DateTime.Now.Date.Day.ToString() + "-" + DateTime.Now.Date.Month.ToString() + "-" + DateTime.Now.Date.Year.ToString() + " " + DateTime.Now.Date.Hour.ToString() + ":" + DateTime.Now.Date.Minute.ToString() + ":" + DateTime.Now.Second.ToString() + " :: " + text;
        }

Вот вам пример форматной строки:

C#
1
string.Format("{0:dd-MM-yyyy HH:mm:ss} :: {1}", DateTime.Now, text);

Далее, если вы используете вывод в псевдоконсоль на форме, то делайте просто унаследованый класс от StreamWriter и пред определяйте методы
WriteLine(…)
Write(…)
Вот пример такого класса:

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
internal class RichTextBoxWriter : StreamWriter
{
    public static RichTextBoxWriter Instance = new RichTextBoxWriter();
 
    public RichTextBox OutputBox;
 
    public RichTextBoxWriter()
        : base(new FileStream(Assembly.GetExecutingAssembly().GetName().Name + ".log", FileMode.Create))
    {
        this.AutoFlush = true;
 
        if (base.BaseStream.Position != 0)
        {
            base.WriteLine();
            base.WriteLine();
        }
    }
 
    public override void WriteLine(string value)
    {
        _Write(value + Environment.NewLine);
    }
 
    public override void WriteLine(string format, params object[] arg)
    {
        _Write(String.Format(format, arg) + Environment.NewLine);
    }
 
    public override void WriteLine()
    {
        _Write(Environment.NewLine);
    }
 
    public override void Write(string value)
    {
        _Write(value);
    }
 
    public override void Write(string format, params object[] arg)
    {
        _Write(String.Format(format, arg));
    }
 
    // Generic Write Method
 
    private void _Write(string text)
    {
        if (!OutputBox.IsDisposed)
        {
            Action f = () =>
            {
                OutputBox.AppendText(text);
                OutputBox.ScrollToBottom();
            };
 
            if (OutputBox.InvokeRequired)
                // Не ждем завершение UI операции.
                OutputBox.BeginInvoke(f);
            else
                f();
        }
 
        if (!string.IsNullOrWhiteSpace(text))
            base.Write(String.Format("[{0:yyyy.MM.dd HH:mm:ss.ffff}] {1}", DateTime.Now, text));
    }
}

Использование:

C#
1
2
3
4
5
6
// предопределяем класс, назначаем вывод через него
Console.SetOut(RichTextBoxWriter.Instance);
// говорим куда выводить
RichTextBoxWriter.Instance.OutputBox = this.rtbConsole;
// далее просто пишем
Console.WriteLine("bla bla {0} bla", bla);
C#
1
OutputBox.ScrollToBottom();

у вас работать не будет, это импортированный метод, используйте

C#
1
OutputBox.ScrollToCaret();



2



1318 / 991 / 127

Регистрация: 08.12.2009

Сообщений: 1,299

25.12.2010, 22:43

5

Цитата
Сообщение от SSTREGG
Посмотреть сообщение

окно не успевает создаться

или наоборот, после её «уничтожения»

VS закрывал и почитал) сам уже смеюсь))



0



10 / 12 / 2

Регистрация: 13.01.2010

Сообщений: 363

26.12.2010, 12:59

 [ТС]

6

Цитата
Сообщение от Mikant
Посмотреть сообщение

самому не стыдно, разор?

стыдно конечно. Но я и не говорил что я программист, я совсем новичок ещё, можно сказать. Задача была — написать программу, а не хорошо её написать.



0



  • Remove From My Forums
  • Вопрос

  • В потоке происходит обращение к форме.

    _textBox.Invoke(new Log((s) => _textBox.Text = s), "привет! "); ***

    Всё хорошо работает. Сворачиваю программу в трей и когда вызываю её из трея:

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
          this.Visible   = true;
          this.WindowState = FormWindowState.Normal;
        }

    …появляется ошибка:

    Невозможно вызвать Invoke или BeginInvoke для элемента управления до завершения создания дескриптора окна.

    (ошибка указывает на ***)

    • Перемещено

      1 октября 2010 г. 21:21
      MSDN Forums Consolidation (От:Visual C#)

Ответы

    • Помечено в качестве ответа
      I.Vorontsov
      7 июля 2010 г. 6:12

  • Ошибка неверный сертификат ssl дбд
  • Ошибка невозвратных затрат это
  • Ошибка неверный расход воздуха через клапан адсорбера
  • Ошибка невозвратных затрат когнитивное искажение
  • Ошибка неверный размер тома veracrypt