2016-11-24 83 views
0

在我的类中有两个方法异步GetDataAsync和不同步GetData()。异步方法抛出奇怪的异常“最创建DependencySource ...”

class Helper 
{ 
    public IList<Data> GetData(someargs) {} 
    public Task<IList<Data>> GetDataAsync(someargs) 
    { 
     return Task.Run(()=>Getdata(someargs) 
    )}; 
} 

class CustomTextBox: TextBox 
{ 
    //... 
    void async TextChanged(object sender, TextChangedEventArgs e) 
    { 
     //I create CustomWindow 
     window = new CustomWindow(this); 
     window.Closed += delegate 
     { 
      window = null; 
     }; 
     //var data = helper.GetData(); work but if ... 
     var data = await helper.GetDataAsync(); 
     if (data != null) 
      { 
       foreach (var item in data) 
       { 
        //custom Listbox with observablecollection... add item 
        window.CustomList.List.Add(item); 
       } 
      } 
      windowCompletion.Show(); //in this step throw exception why??? 
    } 
} 

为什么会抛出异常?使用同步方法一切正常。消息:“必须在与DependencyObject相同的线程上创建DependencySource。”这就像我更新用户界面不是UI线程,但异步/等待大多数解决这个问题。

堆栈跟踪:

в System.Windows.FrameworkTemplate.LoadTemplateXaml(XamlReader templateReader, XamlObjectWriter currentWriter) 
в System.Windows.FrameworkTemplate.LoadTemplateXaml(XamlObjectWriter objectWriter) 
в System.Windows.FrameworkTemplate.LoadOptimizedTemplateContent(DependencyObject container, IComponentConnector componentConnector, IStyleConnector styleConnector, List`1 affectedChildren, UncommonField`1 templatedNonFeChildrenField) 
в System.Windows.FrameworkTemplate.LoadContent(DependencyObject container, List`1 affectedChildren) 
в System.Windows.StyleHelper.ApplyTemplateContent(UncommonField`1 dataField, DependencyObject container, FrameworkElementFactory templateRoot, Int32 lastChildIndex, HybridDictionary childIndexFromChildID, FrameworkTemplate frameworkTemplate) 
в System.Windows.FrameworkTemplate.ApplyTemplateContent(UncommonField`1 templateDataField, FrameworkElement container) 
в System.Windows.FrameworkElement.ApplyTemplate() 
в System.Windows.FrameworkElement.MeasureCore(Size availableSize) 
в System.Windows.UIElement.Measure(Size availableSize) 
в System.Windows.Controls.Border.MeasureOverride(Size constraint) 
в System.Windows.FrameworkElement.MeasureCore(Size availableSize) 
в System.Windows.UIElement.Measure(Size availableSize) 
в System.Windows.Controls.Control.MeasureOverride(Size constraint) 
в System.Windows.FrameworkElement.MeasureCore(Size availableSize) 
в System.Windows.UIElement.Measure(Size availableSize) 
в System.Windows.Controls.VirtualizingStackPanel.MeasureChild(IItemContainerGenerator& generator, IContainItemStorage& itemStorageProvider, IContainItemStorage& parentItemStorageProvider, Object& parentItem, Boolean& hasUniformOrAverageContainerSizeBeenSet, Double& computedUniformOrAverageContainerSize, Double& computedUniformOrAverageContainerPixelSize, Boolean& computedAreContainersUniformlySized, IList& items, Object& item, IList& children, Int32& childIndex, Boolean& visualOrderChanged, Boolean& isHorizontal, Size& childConstraint, Rect& viewport, VirtualizationCacheLength& cacheSize, VirtualizationCacheLengthUnit& cacheUnit, Boolean& foundFirstItemInViewport, Double& firstItemInViewportOffset, Size& stackPixelSize, Size& stackPixelSizeInViewport, Size& stackPixelSizeInCacheBeforeViewport, Size& stackPixelSizeInCacheAfterViewport, Size& stackLogicalSize, Size& stackLogicalSizeInViewport, Size& stackLogicalSizeInCacheBeforeViewport, Size& stackLogicalSizeInCacheAfterViewport, Boolean& mustDisableVirtualization, Boolean isBeforeFirstItem, Boolean isAfterFirstItem, Boolean isAfterLastItem, Boolean skipActualMeasure, Boolean skipGeneration, Boolean& hasBringIntoViewContainerBeenMeasured, Boolean& hasVirtualizingChildren) 
в System.Windows.Controls.VirtualizingStackPanel.MeasureOverrideImpl(Size constraint, Nullable`1& lastPageSafeOffset, List`1& previouslyMeasuredOffsets, Nullable`1& lastPagePixelSize, Boolean remeasure) 
в System.Windows.Controls.VirtualizingStackPanel.MeasureOverride(Size constraint) 
в System.Windows.FrameworkElement.MeasureCore(Size availableSize) 
в System.Windows.UIElement.Measure(Size availableSize) 
в MS.Internal.Helper.MeasureElementWithSingleChild(UIElement element, Size constraint) 
в System.Windows.Controls.ItemsPresenter.MeasureOverride(Size constraint) 
в System.Windows.FrameworkElement.MeasureCore(Size availableSize) 
в System.Windows.UIElement.Measure(Size availableSize) 
в MS.Internal.Helper.MeasureElementWithSingleChild(UIElement element, Size constraint) 
в System.Windows.Controls.ScrollContentPresenter.MeasureOverride(Size constraint) 
в System.Windows.FrameworkElement.MeasureCore(Size availableSize) 
в System.Windows.UIElement.Measure(Size availableSize) 
в System.Windows.Controls.Grid.MeasureCell(Int32 cell, Boolean forceInfinityV) 
в System.Windows.Controls.Grid.MeasureCellsGroup(Int32 cellsHead, Size referenceSize, Boolean ignoreDesiredSizeU, Boolean forceInfinityV, Boolean& hasDesiredSizeUChanged) 
в System.Windows.Controls.Grid.MeasureCellsGroup(Int32 cellsHead, Size referenceSize, Boolean ignoreDesiredSizeU, Boolean forceInfinityV) 
в System.Windows.Controls.Grid.MeasureOverride(Size constraint) 
в System.Windows.FrameworkElement.MeasureCore(Size availableSize) 
в System.Windows.UIElement.Measure(Size availableSize) 
в System.Windows.Controls.ScrollViewer.MeasureOverride(Size constraint) 
в System.Windows.FrameworkElement.MeasureCore(Size availableSize) 
в System.Windows.UIElement.Measure(Size availableSize) 
в System.Windows.Controls.Border.MeasureOverride(Size constraint) 
в System.Windows.FrameworkElement.MeasureCore(Size availableSize) 
в System.Windows.UIElement.Measure(Size availableSize) 
в System.Windows.Controls.Control.MeasureOverride(Size constraint) 
в System.Windows.FrameworkElement.MeasureCore(Size availableSize) 
в System.Windows.UIElement.Measure(Size availableSize) 
в System.Windows.Controls.Control.MeasureOverride(Size constraint) 
в System.Windows.FrameworkElement.MeasureCore(Size availableSize) 
в System.Windows.UIElement.Measure(Size availableSize) 
в MS.Internal.Helper.MeasureElementWithSingleChild(UIElement element, Size constraint) 
в System.Windows.Controls.ContentPresenter.MeasureOverride(Size constraint) 
в System.Windows.FrameworkElement.MeasureCore(Size availableSize) 
в System.Windows.UIElement.Measure(Size availableSize) 
в System.Windows.Controls.Border.MeasureOverride(Size constraint) 
в System.Windows.FrameworkElement.MeasureCore(Size availableSize) 
в System.Windows.UIElement.Measure(Size availableSize) 
в System.Windows.Window.MeasureOverrideHelper(Size constraint) 
в System.Windows.Window.MeasureOverride(Size availableSize) 
в System.Windows.FrameworkElement.MeasureCore(Size availableSize) 
в System.Windows.UIElement.Measure(Size availableSize) 
в System.Windows.Interop.HwndSource.SetLayoutSize() 
в System.Windows.Interop.HwndSource.set_RootVisualInternal(Visual value) 
в System.Windows.Interop.HwndSource.set_RootVisual(Visual value) 
в System.Windows.Window.SetRootVisual() 
в System.Windows.Window.SetRootVisualAndUpdateSTC() 
в System.Windows.Window.SetupInitialState(Double requestedTop, Double requestedLeft, Double requestedWidth, Double requestedHeight) 
в System.Windows.Window.CreateSourceWindow(Boolean duringShow) 
в System.Windows.Window.CreateSourceWindowDuringShow() 
в System.Windows.Window.SafeCreateWindowDuringShow() 
в System.Windows.Window.ShowHelper(Object booleanBox) 
в System.Windows.Window.Show() 
MoveNext() 
--- Конец трассировка стека из предыдущего расположения, где возникло исключение --- 
в System.Runtime.CompilerServices.AsyncMethodBuilderCore.<>c.<ThrowAsync>b__6_0(Object state) 
в System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs) 
в System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler) 
в System.Windows.Threading.DispatcherOperation.InvokeImpl() 
в System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state) 
в MS.Internal.CulturePreservingExecutionContext.CallbackWrapper(Object obj) 
в System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) 
в System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) 
в System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) 
в MS.Internal.CulturePreservingExecutionContext.Run(CulturePreservingExecutionContext executionContext, ContextCallback callback, Object state) 
в 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(Object o) 
в System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs) 
в System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler) 
в System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs) 
в 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.Application.RunDispatcher(Object ignore) 
в System.Windows.Application.RunInternal(Window window) 
в System.Windows.Application.Run(Window window) 
в System.Windows.Application.Run() 
в CodeBox.App.Main() 
в System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args) 
в System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) 
в Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() 
в System.Threading.ThreadHelper.ThreadStart_Context(Object state) 
в System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) 
в System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) 
в System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) 
в System.Threading.ThreadHelper.ThreadStart() 

回答

1

你在Getdata代码(不幸的是,未示出)与/相互作用产生了一些UI元素。如果没有在UI线程上完成,则禁止这样做。错误信息很清楚,我认为。因此,要么通过将UI工作移至UI线程来重构该代码,要么不要使用异步。由于它不是本地异步方法(因为您使用的是Task.Run,它使用新线程,因此也是例外),因此您可能想问问自己,您的应用程序是否真的有利于以这种方式使用异步。

+0

谢谢,我发现我在哪里操纵UI。奇怪,但是当我在我的项目中使用imagesource uri创建数据对象时。这是可能的? – itihonov

+0

你可以发布GetData()的代码吗? –