Ddu method not found void system windows threading dispatcher invoke

So the following works fine on my computer, however on another person's computer it is always throwing an error of:
  • Remove From My Forums
  • Question

  • So the following works fine on my computer, however on another person’s computer it is always throwing an error of:

    «Method not found: ‘System.Object System.Windows.Threading.Dispatcher.Invoke(System.Delegate, System.Object[])'»

    I don’t think I’m doing anything abnormal that should really cause problems, and the code does work locally, but the other person gets the error every time.  Any thoughts?

    Here is sample code that would effectively reproduce the error:

    public delegate void CallBack();private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        
    Thread t = new Thread(LoadData);
        t.Start();
    }

    private void LoadData()
    {

        ChangeToWaitCursor();
    }


    public void ChangeToWaitCursor()
    {
        
    if (this.Dispatcher.CheckAccess())
        {
            Cursor =
    Cursors.Wait;
        }
        else
        {
            
    CallBack d = new CallBack(ChangeToWaitCursor);
            
    this.Dispatcher.Invoke(d, null);
        }
    }


    • Edited by

      Monday, August 18, 2008 4:28 PM
      Has Code

Answers

  • I dug into it a bit more — the dispatcher method I am using was introduced in .Net 3.5 SP1, which the user does not have:

    http://msdn.microsoft.com/en-us/library/cc647509.aspx

    Just a note here — in Visual Studio I only see the new SP1 Invoke Methods, which have a convention of Dispatcher.Invoke(Delegate, … [more params]), instead of the 3.5 convention of Dispatcher.Invoke(DispatcherPriority, … [more params]).  However, the original methods still function fine, despite the fact that they don’t show up in Intellisense.  So in some cases like mine, it may be necessary to continue to use the older methods. 

    SP1 Methods:

    Invoke(Delegate, array<Object>[]()[])
    Invoke(Delegate, TimeSpan, array<Object>[]()[])
    Invoke(Delegate, DispatcherPriority, array<Object>[]()[])
    Invoke(Delegate, TimeSpan, DispatcherPriority, array<Object>[]()[])

    3.5 Original Methods:

    Invoke(DispatcherPriority, Delegate)
    Invoke(DispatcherPriority, Delegate, Object)
    Invoke(DispatcherPriority, TimeSpan, Delegate)
    Invoke(DispatcherPriority, Delegate, Object, array<Object>[]()[])
    Invoke(DispatcherPriority, TimeSpan, Delegate, Object)
    Invoke(DispatcherPriority, TimeSpan, Delegate, Object, array<Object>[]()[])

    • Edited by
      rutt
      Monday, August 18, 2008 7:17 PM
      Add detail.
    • Marked as answer by
      rutt
      Monday, August 18, 2008 7:17 PM
    • Marked as answer by
      rutt
      Monday, August 18, 2008 7:17 PM

Попробуй это:

updateStatusDelegate usd = new updateStatusDelegate(progressBar.SetValue);
Dispatcher.CurrentDispatcher.Invoke(
    usd, 
    DispatcherPriority.Background, 
    new object[] { ProgressBar.ValueProperty, Convert.ToDouble(perc) });

Invoke — это не статический метод. Вы должны вызвать его в экземпляре класса. Вы можете использовать статическое свойство Диспетчер. для получения (или создания) диспетчера, связанного с текущим потоком.

(Кстати, вы ошибаетесь, что это будет работать с другой версией фреймворка.)


Я взял следующую программу (все в MainWindow.xaml.cs):

public partial class MainWindow : Window
{
    private string perc = ".25";

    public MainWindow()
    {
        InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        updateStatusDelegate usd = new updateStatusDelegate(
            progressBar.SetValue);
        Dispatcher.Invoke(usd, 
            System.Windows.Threading.DispatcherPriority.Background, 
            new object[] { 
                System.Windows.Controls.ProgressBar.ValueProperty, 
                Convert.ToDouble(perc) });

        var dbl = Convert.ToDouble(perc);
        perc = (dbl + .1).ToString();
    }
}
public delegate void updateStatusDelegate(DependencyProperty dp, object value);

и запустили его для версий 3.0, 3.5 (sp1) и 4.0. Работает на каждой версии.

Это подводит меня к трем выводам. Во-первых, perc может не быть строкой, а Convert.ToDouble не имеет перегрузки для преобразования того типа, которым он на самом деле является. Во-вторых, компьютер пользователя поврежден и нуждается в хорошей очистке (протрите, переустановите). В-третьих, ваша проблема в другом, и вы think здесь вы получаете исключение, но на самом деле это где-то еще.

Попробуйте следующее:

updateStatusDelegate usd = new updateStatusDelegate(progressBar.SetValue);
Dispatcher.CurrentDispatcher.Invoke(
    usd, 
    DispatcherPriority.Background, 
    new object[] { ProgressBar.ValueProperty, Convert.ToDouble(perc) });

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

(Кстати, вы неверны, что это будет работать с другой версией фреймворка.)


Я выполнил следующую программу (все в MainWindow.xaml.cs):

public partial class MainWindow : Window
{
    private string perc = ".25";

    public MainWindow()
    {
        InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        updateStatusDelegate usd = new updateStatusDelegate(
            progressBar.SetValue);
        Dispatcher.Invoke(usd, 
            System.Windows.Threading.DispatcherPriority.Background, 
            new object[] { 
                System.Windows.Controls.ProgressBar.ValueProperty, 
                Convert.ToDouble(perc) });

        var dbl = Convert.ToDouble(perc);
        perc = (dbl + .1).ToString();
    }
}
public delegate void updateStatusDelegate(DependencyProperty dp, object value);

и запустили таргетинг на 3.0, 3.5 (sp1) и 4.0. Он работает с каждой версией.

Это приводит меня к трем выводам. Во-первых, perc может не быть строкой, а Convert.ToDouble не имеет перегрузки для преобразования типа, который он на самом деле. Во-вторых, компьютер пользователя поврежден и нуждается в хорошей очистке (протрите, переустановите). В-третьих, ваша проблема в другом месте, и вы думаете, что это то, где вы получаете исключение, но на самом деле это где-то еще.

I’m attaching the stacktrace

   en Project.API.Client.ProjectAPI..ctor(DelegatingHandler[] handlers)
   en Project.API.Client.ProjectAPI..ctor(Uri baseUri, DelegatingHandler[] handlers) en C:UsersdarkfileSourcereposProjectProject.API.ClientProjectAPI.cs:línea 77
   en Project.GUI.App.RegisterIoC() en C:UsersdarkfileSourcereposProject.GUIApp.xaml.cs:línea 108
   en Project.GUI.App.OnStartup(StartupEventArgs e) en C:UsersdarkfileSourcereposProject.GUIApp.xaml.cs:línea 37
   en System.Windows.Application.<.ctor>b__1_0(Object unused)
   en System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   en System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
   en System.Windows.Threading.DispatcherOperation.InvokeImpl()
   en System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
   en MS.Internal.CulturePreservingExecutionContext.CallbackWrapper(Object obj)
   en System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   en System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   en System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   en MS.Internal.CulturePreservingExecutionContext.Run(CulturePreservingExecutionContext executionContext, ContextCallback callback, Object state)
   en System.Windows.Threading.DispatcherOperation.Invoke()
   en System.Windows.Threading.Dispatcher.ProcessQueue()
   en System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   en MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   en MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
   en System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   en System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
   en System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
   en MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   en MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
   en System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
   en System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
   en System.Windows.Application.RunDispatcher(Object ignore)
   en System.Windows.Application.RunInternal(Window window)
   en System.Windows.Application.Run(Window window)
   en System.Windows.Application.Run()
   en Project.GUI.App.Main()

Добрый день, не получается реализовать такую систему:
Есть 2 класса

C#
1
public partial class MainWindow : Window

И есть статический класс, в котором я реализую различные методы.
Вот 1 из методов:

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public void MakeShure(object obj)
        {
           this.Dispatcher.Invoke(()=>
             {
                 List<Student> stdlst = obj as List<Student>;
                 Random rnd = new Random();
                 foreach (Student el in stdlst)
                 {
 
                     var lble = el._ChangedControl as System.Windows.Controls.Label;
                     lble.Content = "HEY " + el._firstName;
                     lble.Foreground = new SolidColorBrush(Color.FromArgb((byte)rnd.Next(0, 255), (byte)rnd.Next(0, 255), (byte)rnd.Next(0, 255), 0));
                     lble.Refresh();
                     System.Threading.Thread.Sleep(50);
                 }
             });

Nак я вызываю метод по нажатию кнопки:

C#
1
2
3
4
            Thread tstTrd;
            SocialDataOperation noon = new SocialDataOperation();
            tstTrd = new Thread(noon.MakeShure);
            tstTrd.Start(tst);

Данная конструкция не работает, еще и налагает условия, на сколько я понимаю, класс должен быть не статический и наследником Window, что бы я мог использовать тот самый заветный диспатчер, иначе я не могу изменять label который был создан в основном потоке, тлен.
Подскажите пожалуйста как использовать Invoke парвильно.

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь

    System.MissingMethodException: Метод не найден: «System.Windows.Threading.DispatcherOperation System.Windows.Threading.Dispatcher.BeginInvoke(System.Delegate, System.Object[])».

       в Hitori.Controls.Clock.DisplayTime(TimeSpan ts)

       в Hitori.Controls.Clock.Start() в D:ProjectsHitoriSourceHitoriControlsClock.xaml.cs:строка 53

       в Hitori.MainWindow.StartTimer() в D:ProjectsHitoriSourceHitoriViewsMainWindow.xaml.cs:строка 368

       в Hitori.MainWindowPresenter.Handle_NewGame_OR_GiveUp() в D:ProjectsHitoriSourceHitoriPresentersMainWindowPresenter.cs:строка 148

       в Hitori.MainWindow.btnStartFinish_Click(Object sender, MouseButtonEventArgs e) в D:ProjectsHitoriSourceHitoriViewsMainWindow.xaml.cs:строка 146

       в Hitori.Controls.PNGButton.OnMouseUp(MouseButtonEventArgs e) в D:ProjectsHitoriSourceHitoriControlsPNGButton.xaml.cs:строка 288

       в Hitori.Controls.PNGButton.image_MouseUp(Object sender, MouseButtonEventArgs e) в D:ProjectsHitoriSourceHitoriControlsPNGButton.xaml.cs:строка 185

       в System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)

       в System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)

       в System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)

       в System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)

       в System.Windows.UIElement.RaiseEventImpl(RoutedEventArgs args)

       в System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)

       в System.Windows.Input.InputManager.ProcessStagingArea()

       в System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)

       в System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)

       в System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)

       в System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)

       в System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)

       в MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)

       в MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)

       в System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter)

       в System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)

       в System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Boolean isSingleParameter)

       в System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority priority, Delegate method, Object arg)

       в MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)

       в MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)

       в System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)

       в System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)

       в System.Windows.Threading.Dispatcher.Run()

       в System.Windows.Application.RunInternal(Window window)

       в System.Windows.Application.Run(Window window)

       в System.Windows.Application.Run()

       в Hitori.App.Main() в D:ProjectsHitoriSourceHitoriobjDebugApp.g.cs:строка 0

Понравилась статья? Поделить с друзьями:
  • Ddt4all скачать на русском для windows
  • Ddt4all renault установка на ноутбук windows
  • Ddst для windows 10 скачать бесплатно
  • Ddl библиотека скачать программу windows 10
  • Dde server window при выключении компьютера windows 10