Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 线程调用主窗口?_C#_Multithreading_Invoke_Mainwindow - Fatal编程技术网

C# 线程调用主窗口?

C# 线程调用主窗口?,c#,multithreading,invoke,mainwindow,C#,Multithreading,Invoke,Mainwindow,因此,基本上我有一个main窗口,一个类SetupViewModel定义在一个单独的cs文件中,另一个类ImageViewModel定义在一个单独的cs文件中; 我想知道我是否可以从ImageViewModel调用main窗口中的操作。详情如下: 在ImageViewModel中,调用MainWindow中的更改,如下所示(在MainWindow中执行以下代码): ViewType变量在SetupViewModel中定义如下 private int _viewType; public

因此,基本上我有一个
main窗口
,一个类
SetupViewModel
定义在一个单独的cs文件中,另一个类
ImageViewModel
定义在一个单独的cs文件中; 我想知道我是否可以从
ImageViewModel
调用
main窗口中的操作。详情如下:

  • 在ImageViewModel中,调用MainWindow中的更改,如下所示(在
    MainWindow
    中执行以下代码):

  • ViewType变量在
    SetupViewModel
    中定义如下

    private int _viewType;
        public int ViewType
        {
            get
            {
                return _viewType;
            }
            set
            {
                _viewType = value;
                OnPropertyChanged("ViewType");
            }
        }
    
  • 我是这样做的,但没有成功;调用
    ImageViewModel
    中的代码:

    试一试 { Action SwitchTo2DView=委托() { ((CaptureSetupViewModel)System.Windows.Application.Current.MainWindow.DataContext).ViewType=Convert.ToInt32(ViewTypes.ViewType2D);}

                System.Windows.Application.Current.MainWindow.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, SwitchTo2DView);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Caught exception: " + ex.ToString());
            }
    
例外情况是:

System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NullReferenceException: Object reference not set to an instance of an object.
   at CaptureSetupDll.ViewModel.LiveImageViewModel.<StartZStackPreview>b__2c()
   --- End of inner exception stack trace ---
   at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
   at System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
   at System.Delegate.DynamicInvokeImpl(Object[] args)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter)
   at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
   at System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
   at System.Windows.Threading.DispatcherOperation.InvokeImpl()
   at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
   at System.Threading.ExecutionContext.runTryCode(Object userData)
   at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Windows.Threading.DispatcherOperation.Invoke()
   at System.Windows.Threading.Dispatcher.ProcessQueue()
   at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter)
   at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
   at System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
   at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Boolean isSingleParameter)
   at System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority priority, Delegate method, Object arg)
   at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
   at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
   at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
   at System.Windows.Threading.DispatcherOperation.Wait(TimeSpan timeout)
   at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Boolean isSingleParameter)
   at System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority priority, Delegate method)
   at CaptureSetupDll.ViewModel.LiveImageViewModel.StartZStackPreview()
System.Reflection.TargetInvocationException:调用的目标已引发异常。-->System.NullReferenceException:对象引用未设置为对象的实例。
在CaptureSetupDll.ViewModel.LiveImageViewModel.b_uu2c()中
---内部异常堆栈跟踪的结束---
在System.RuntimeMethodHandle.\u InvokeMethodFast(对象目标、对象[]参数、SignatureStruct&sig、MethodAttributes方法属性、RuntimeTypeHandle类型所有者)
位于System.RuntimeMethodHandle.InvokeMethodFast(对象目标、对象[]参数、签名符号、方法属性、方法属性、RuntimeTypeHandle类型所有者)
在System.Reflection.RuntimeMethodInfo.Invoke(对象obj、BindingFlags invokeAttr、绑定器绑定器、对象[]参数、CultureInfo区域性、布尔skipVisibilityChecks)
位于System.Delegate.DynamicInvokeImpl(对象[]args)
位于System.Windows.Threading.ExceptionWrapper.InternalRealCall(委托回调、对象参数、布尔isSingleParameter)
位于System.Windows.Threading.ExceptionWrapper.TryCatchWhen(对象源、委托回调、对象参数、布尔isSingleParameter、委托catchHandler)
位于System.Windows.Threading.Dispatcher.WrappedInvoke(委托回调、对象参数、布尔isSingleParameter、委托catchHandler)
在System.Windows.Threading.DispatcherOperation.InvokeImpl()中
位于System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(对象状态)
位于System.Threading.ExecutionContext.runTryCode(对象用户数据)
在System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode代码、CleanupCode backoutCode、Object userData)中运行
位于System.Threading.ExecutionContext.RunInternal(ExecutionContext ExecutionContext,ContextCallback回调,对象状态)
在System.Threading.ExecutionContext.Run(ExecutionContext ExecutionContext,ContextCallback回调,对象状态)
在System.Windows.Threading.DispatcherOperation.Invoke()中
在System.Windows.Threading.Dispatcher.ProcessQueue()中
位于System.Windows.Threading.Dispatcher.WndProcHook(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(对象o)上
位于System.Windows.Threading.ExceptionWrapper.InternalRealCall(委托回调、对象参数、布尔isSingleParameter)
位于System.Windows.Threading.ExceptionWrapper.TryCatchWhen(对象源、委托回调、对象参数、布尔isSingleParameter、委托catchHandler)
位于System.Windows.Threading.Dispatcher.WrappedInvoke(委托回调、对象参数、布尔isSingleParameter、委托catchHandler)
位于System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority优先级、TimeSpan超时、委托方法、对象参数、布尔isSingleParameter)
位于System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority优先级、委托方法、对象参数)
位于MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd、Int32 msg、IntPtr wParam、IntPtr lParam)
位于MS.Win32.unsafentivemethods.DispatchMessage(MSG&MSG)
位于System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame框架)
在System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame框架)上
位于System.Windows.Threading.DispatcherOperation.Wait(TimeSpan超时)
位于System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority优先级、TimeSpan超时、委托方法、对象参数、布尔isSingleParameter)
位于System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority优先级,委托方法)
在CaptureSetupDll.ViewModel.LiveImageViewModel.StartZStackPreview()中

我是C#的门外汉,你知道我该怎么做吗?非常感谢。

我敢打赌,在调用这个时,你的DataContext是空的。这意味着调用它可能太早了。这可能意味着你应该把你正在做的事情推到调度程序上

虽然您可以假定在调用此方法时应用程序已完全加载,但不一定为真。若要测试此情况,请在调试期间设置断点,并检查
DataContext
以查看其是否为空

如果为null,则有两种选择。首先,返回。根据调用方法的方式,在加载过程中可能会多次调用该方法。稍后的调用可能会显示非null上下文

另一个选项是在加载应用程序后使用重新调用该方法

这里有一个小伪代码,看起来有点像C#,甚至可以编译:

public void CheckTheDataContext()
{
    // is it null?
    if(this.DataContext == null)
    {
        // then drop an Action re-invoking this method later
        // when the application idles out a bit
        Dispatcher.BeginInvoke((Action)(() =>
        {
            CheckTheDataContext();
        }), System.Windows.Threading.DispatcherPriority.ApplicationIdle);
        return;
    }
    DoSomethingElseWithTheContext(DataContext);
}

什么是InnerException及其堆栈跟踪?Visual Studio打开时显示的异常窗口将提供此信息。您所做的是从第二个线程调用主窗口的正确方式。我正在添加一张图片以显示我看到的内容。@Ramhound:是的,我想我很困惑,所以我在这里寻找
public void CheckTheDataContext()
{
    // is it null?
    if(this.DataContext == null)
    {
        // then drop an Action re-invoking this method later
        // when the application idles out a bit
        Dispatcher.BeginInvoke((Action)(() =>
        {
            CheckTheDataContext();
        }), System.Windows.Threading.DispatcherPriority.ApplicationIdle);
        return;
    }
    DoSomethingElseWithTheContext(DataContext);
}