异步方法抛出奇怪的异常“最创建DependencySource ...”

时间:2016-11-24 20:13:17

标签: c# asynchronous async-await task dependencyobject

在我的类中有两个方法异步GetDataAsync而不同步GetData()。

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线程中更新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 个答案:

答案 0 :(得分:1)

Getdata中的代码(遗憾的是,未显示)与/创建了一些UI元素。如果没有在UI线程上完成,那是禁止的。错误消息我很清楚。因此,要么通过将UI工作移动到UI线程来重构代码,要么不使用异步。由于它不是本机异步方法(因为您正在使用Task.Run,它使用新线程,因此例外)您可能想问自己,您的应用程序是否真的有益于以这种方式使用异步。