Slow Save in Entity Framework, very specific entity - sql-server

I have a very interesting (and confusing) issue for quite a while, but cannot get to the bottom of it
I have a WPF Project built on Entity Framework, with about 100 different entities/tables, which all work smoothly. except for one entity type, named SaleProduct
Saving a SaleProduct takes about 5 minutes, sometimes even more (other entities take under 2 seconds usually). And only in the window.
For testing purposes, I put this code in app startup:
Using d = GetSystemContext(True)
Dim sp = d.Find(Of SaleProduct)(66246)
sp.DiscountAmount += 1
d.SaveChanges()
End Using
And saving there is OK(11 seconds, bearable).
But when I open a window with the SaleProduct as the DataContext and save there, it takes several minutes.
So, I would like to debug this. Maybe I have some bad code somewhere. But I'm not managing with this either. If I press pause in Visual Studio while the app is stuck saving, it freezes on the SaveChanges line, meaning not some custom code. So what difference should it make if we are in the app startup or in the window?
But lets take this a step further, I disabled Just My Code to get a better picture of whats freezing. And it gets stuck here:
InternalDispatcher.cs
try
{
interceptionContext.MutableData.SetExecuted(operation(target, interceptionContext));
}
Where the target is a pretty simple SQL statement
UPDATE [dbo].[Sales]
SET [LastEditedOn] = #0
WHERE ([ID] = #1)
SELECT [AutoPurchaseDate], [GrantingDate], [ReceivedOn], [Name], [TotalVatRate]
FROM [dbo].[Sales]
WHERE ##ROWCOUNT > 0 AND [ID] = #1
Running this in SSMS takes <1 seconds.
But looking at the complete call stack I see that actually its stuck someplace in System.Data.dll. Though try as I might I cant find its .pdb.
So I tried to use decompile, but I get an error
Unable to compile the module
Even though, in the modules window the status is "Symbols loaded".
So I cannot pinpoint precisely.
For kicks, I tried upgrading to .net 4.8 (from 4.7). same problem.
What can I do? How to proceed? Where more can I Investigate?
NOTES
Tables Sales and SaleProducts both have Clustered Primary Keys.
Running SELECT * FROM sys.sysprocesses WHERE open_tran = 1 in SSMS while the code is stuck, returns 0 rows.
InSaveChanges, ChangeTracker.Entries returns precisely 2 entities. The SaleProduct, and its parent Sale.
I've posted a Profiler Trace here https://pastebin.com/enLgE0Ln
Here's the full StackTrace if it might help someone
[Managed to Native Transition]
System.Data.dll!SNINativeMethodWrapper.SNIReadSyncOverAsync(System.Runtime.InteropServices.SafeHandle pConn, ref System.IntPtr packet, int timeout) Unknown
System.Data.dll!System.Data.SqlClient.TdsParserStateObject.ReadSniSyncOverAsync() Unknown
System.Data.dll!System.Data.SqlClient.TdsParserStateObject.TryReadNetworkPacket() Unknown
System.Data.dll!System.Data.SqlClient.TdsParserStateObject.TryPrepareBuffer() Unknown
System.Data.dll!System.Data.SqlClient.TdsParserStateObject.TryReadByte(out byte value) Unknown
System.Data.dll!System.Data.SqlClient.TdsParser.TryRun(System.Data.SqlClient.RunBehavior runBehavior, System.Data.SqlClient.SqlCommand cmdHandler, System.Data.SqlClient.SqlDataReader dataStream, System.Data.SqlClient.BulkCopySimpleResultSet bulkCopyHandler, System.Data.SqlClient.TdsParserStateObject stateObj, out bool dataReady) Unknown
System.Data.dll!System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() Unknown
System.Data.dll!System.Data.SqlClient.SqlDataReader.MetaData.get() Unknown
System.Data.dll!System.Data.SqlClient.SqlCommand.FinishExecuteReader(System.Data.SqlClient.SqlDataReader ds, System.Data.SqlClient.RunBehavior runBehavior, string resetOptionsString, bool isInternal, bool forDescribeParameterEncryption, bool shouldCacheForAlwaysEncrypted) Unknown
System.Data.dll!System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(System.Data.CommandBehavior cmdBehavior, System.Data.SqlClient.RunBehavior runBehavior, bool returnStream, bool async, int timeout, out System.Threading.Tasks.Task task, bool asyncWrite, bool inRetry, System.Data.SqlClient.SqlDataReader ds, bool describeParameterEncryptionRequest) Unknown
System.Data.dll!System.Data.SqlClient.SqlCommand.RunExecuteReader(System.Data.CommandBehavior cmdBehavior, System.Data.SqlClient.RunBehavior runBehavior, bool returnStream, string method, System.Threading.Tasks.TaskCompletionSource<object> completion, int timeout, out System.Threading.Tasks.Task task, out bool usedCache, bool asyncWrite, bool inRetry) Unknown
System.Data.dll!System.Data.SqlClient.SqlCommand.RunExecuteReader(System.Data.CommandBehavior cmdBehavior, System.Data.SqlClient.RunBehavior runBehavior, bool returnStream, string method) Unknown
System.Data.dll!System.Data.SqlClient.SqlCommand.ExecuteReader(System.Data.CommandBehavior behavior, string method) Unknown
> EntityFramework.dll!System.Data.Entity.Infrastructure.Interception.InternalDispatcher<System.Data.Entity.Infrastructure.Interception.IDbCommandInterceptor>.Dispatch<System.Data.Common.DbCommand, System.Data.Entity.Infrastructure.Interception.DbCommandInterceptionContext<System.Data.Common.DbDataReader>, System.Data.Common.DbDataReader>(System.Data.Common.DbCommand target, System.Func<System.Data.Common.DbCommand, System.Data.Entity.Infrastructure.Interception.DbCommandInterceptionContext<System.Data.Common.DbDataReader>, System.Data.Common.DbDataReader> operation, System.Data.Entity.Infrastructure.Interception.DbCommandInterceptionContext<System.Data.Common.DbDataReader> interceptionContext, System.Action<System.Data.Entity.Infrastructure.Interception.IDbCommandInterceptor, System.Data.Common.DbCommand, System.Data.Entity.Infrastructure.Interception.DbCommandInterceptionContext<System.Data.Common.DbDataReader>> executing, System.Action<System.Data.Entity.Infrastructure.Interception.IDbCommandInterceptor, System.Data.Common.DbCommand, System.Data.Entity.Infrastructure.Interception.DbCommandInterceptionContext<System.Data.Common.DbDataReader>> executed) Line 138 C#
EntityFramework.dll!System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(System.Data.Common.DbCommand command, System.Data.Entity.Infrastructure.Interception.DbCommandInterceptionContext interceptionContext) Line 103 C#
EntityFramework.dll!System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.Execute(System.Collections.Generic.Dictionary<int, object> identifierValues, System.Collections.Generic.List<System.Collections.Generic.KeyValuePair<System.Data.Entity.Core.Mapping.Update.Internal.PropagatorResult, object>> generatedValues) Line 118 C#
EntityFramework.dll!System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update() Line 532 C#
EntityFramework.dll!System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction<int>(System.Func<int> func, System.Data.Entity.Infrastructure.IDbExecutionStrategy executionStrategy, bool startLocalTransaction, bool releaseConnectionOnSuccess) Line 2203 C#
EntityFramework.dll!System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(System.Data.Entity.Core.Objects.SaveOptions options, System.Data.Entity.Infrastructure.IDbExecutionStrategy executionStrategy, bool startLocalTransaction) Line 2148 C#
EntityFramework.SqlServer.dll!System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute<int>(System.Func<int> operation) Unknown
EntityFramework.dll!System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(System.Data.Entity.Core.Objects.SaveOptions options, bool executeInExistingTransaction) Line 2046 C#
EntityFramework.dll!System.Data.Entity.Internal.InternalContext.SaveChanges() Line 483 C#
Machshevet.dll!Machshevet.Core.RecordContext.SaveChanges() Line 762 Basic
Machshevet.dll!Machshevet.Windows.RecordWindow.Save() Line 169 Basic
Machshevet.dll!Machshevet.Windows.RecordWindow.<closure>.<lambda35-0>() Line 44 Basic
PresentationCore.dll!System.Windows.Input.CommandBinding.OnExecuted(object sender, System.Windows.Input.ExecutedRoutedEventArgs e) Unknown
PresentationCore.dll!System.Windows.Input.CommandManager.ExecuteCommandBinding(object sender, System.Windows.Input.ExecutedRoutedEventArgs e, System.Windows.Input.CommandBinding commandBinding) Unknown
PresentationCore.dll!System.Windows.Input.CommandManager.FindCommandBinding(System.Windows.Input.CommandBindingCollection commandBindings, object sender, System.Windows.RoutedEventArgs e, System.Windows.Input.ICommand command, bool execute) Unknown
PresentationCore.dll!System.Windows.Input.CommandManager.FindCommandBinding(object sender, System.Windows.RoutedEventArgs e, System.Windows.Input.ICommand command, bool execute) Unknown
PresentationCore.dll!System.Windows.Input.CommandManager.OnExecuted(object sender, System.Windows.Input.ExecutedRoutedEventArgs e) Unknown
PresentationCore.dll!System.Windows.RoutedEventArgs.InvokeHandler(System.Delegate handler, object target) Unknown
PresentationCore.dll!System.Windows.RoutedEventHandlerInfo.InvokeHandler(object target, System.Windows.RoutedEventArgs routedEventArgs) Unknown
PresentationCore.dll!System.Windows.EventRoute.InvokeHandlersImpl(object source, System.Windows.RoutedEventArgs args, bool reRaised) Unknown
PresentationCore.dll!System.Windows.UIElement.RaiseEventImpl(System.Windows.DependencyObject sender, System.Windows.RoutedEventArgs args) Unknown
PresentationCore.dll!System.Windows.Input.RoutedCommand.ExecuteImpl(object parameter, System.Windows.IInputElement target, bool userInitiated) Unknown
PresentationCore.dll!System.Windows.Input.CommandManager.TransferEvent(System.Windows.IInputElement newSource, System.Windows.Input.ExecutedRoutedEventArgs e) Unknown
PresentationCore.dll!System.Windows.Input.CommandManager.OnExecuted(object sender, System.Windows.Input.ExecutedRoutedEventArgs e) Unknown
PresentationCore.dll!System.Windows.RoutedEventArgs.InvokeHandler(System.Delegate handler, object target) Unknown
PresentationCore.dll!System.Windows.RoutedEventHandlerInfo.InvokeHandler(object target, System.Windows.RoutedEventArgs routedEventArgs) Unknown
PresentationCore.dll!System.Windows.EventRoute.InvokeHandlersImpl(object source, System.Windows.RoutedEventArgs args, bool reRaised) Unknown
PresentationCore.dll!System.Windows.UIElement.RaiseEventImpl(System.Windows.DependencyObject sender, System.Windows.RoutedEventArgs args) Unknown
PresentationCore.dll!System.Windows.Input.RoutedCommand.ExecuteImpl(object parameter, System.Windows.IInputElement target, bool userInitiated) Unknown
PresentationFramework.dll!MS.Internal.Commands.CommandHelpers.CriticalExecuteCommandSource(System.Windows.Input.ICommandSource commandSource, bool userInitiated) Unknown
PresentationFramework.dll!System.Windows.Controls.Primitives.ButtonBase.OnClick() Unknown
PresentationFramework.dll!System.Windows.Controls.Button.OnClick() Unknown
System.Windows.Controls.Ribbon.dll!System.Windows.Controls.Ribbon.RibbonButton.OnClick() Unknown
PresentationFramework.dll!System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(System.Windows.Input.MouseButtonEventArgs e) Unknown
PresentationCore.dll!System.Windows.RoutedEventArgs.InvokeHandler(System.Delegate handler, object target) Unknown
PresentationCore.dll!System.Windows.RoutedEventHandlerInfo.InvokeHandler(object target, System.Windows.RoutedEventArgs routedEventArgs) Unknown
PresentationCore.dll!System.Windows.EventRoute.InvokeHandlersImpl(object source, System.Windows.RoutedEventArgs args, bool reRaised) Unknown
PresentationCore.dll!System.Windows.UIElement.ReRaiseEventAs(System.Windows.DependencyObject sender, System.Windows.RoutedEventArgs args, System.Windows.RoutedEvent newEvent) Unknown
PresentationCore.dll!System.Windows.UIElement.OnMouseUpThunk(object sender, System.Windows.Input.MouseButtonEventArgs e) Unknown
PresentationCore.dll!System.Windows.RoutedEventArgs.InvokeHandler(System.Delegate handler, object target) Unknown
PresentationCore.dll!System.Windows.RoutedEventHandlerInfo.InvokeHandler(object target, System.Windows.RoutedEventArgs routedEventArgs) Unknown
PresentationCore.dll!System.Windows.EventRoute.InvokeHandlersImpl(object source, System.Windows.RoutedEventArgs args, bool reRaised) Unknown
PresentationCore.dll!System.Windows.UIElement.RaiseEventImpl(System.Windows.DependencyObject sender, System.Windows.RoutedEventArgs args) Unknown
PresentationCore.dll!System.Windows.UIElement.RaiseTrustedEvent(System.Windows.RoutedEventArgs args) Unknown
PresentationCore.dll!System.Windows.Input.InputManager.ProcessStagingArea() Unknown
PresentationCore.dll!System.Windows.Input.InputManager.ProcessInput(System.Windows.Input.InputEventArgs input) Unknown
PresentationCore.dll!System.Windows.Input.InputProviderSite.ReportInput(System.Windows.Input.InputReport inputReport) Unknown
PresentationCore.dll!System.Windows.Interop.HwndMouseInputProvider.ReportInput(System.IntPtr hwnd, System.Windows.Input.InputMode mode, int timestamp, System.Windows.Input.RawMouseActions actions, int x, int y, int wheel) Unknown
PresentationCore.dll!System.Windows.Interop.HwndMouseInputProvider.FilterMessage(System.IntPtr hwnd, MS.Internal.Interop.WindowMessage msg, System.IntPtr wParam, System.IntPtr lParam, ref bool handled) Unknown
PresentationCore.dll!System.Windows.Interop.HwndSource.InputFilterMessage(System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam, ref bool handled) Unknown
WindowsBase.dll!MS.Win32.HwndWrapper.WndProc(System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam, ref bool handled) Unknown
WindowsBase.dll!MS.Win32.HwndSubclass.DispatcherCallbackOperation(object o) Unknown
WindowsBase.dll!System.Windows.Threading.ExceptionWrapper.InternalRealCall(System.Delegate callback, object args, int numArgs) Unknown
WindowsBase.dll!System.Windows.Threading.ExceptionWrapper.TryCatchWhen(object source, System.Delegate callback, object args, int numArgs, System.Delegate catchHandler) Unknown
WindowsBase.dll!System.Windows.Threading.Dispatcher.LegacyInvokeImpl(System.Windows.Threading.DispatcherPriority priority, System.TimeSpan timeout, System.Delegate method, object args, int numArgs) Unknown
WindowsBase.dll!MS.Win32.HwndSubclass.SubclassWndProc(System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam) Unknown
[Native to Managed Transition]
[Managed to Native Transition]
WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrameImpl(System.Windows.Threading.DispatcherFrame frame) Unknown
PresentationFramework.dll!System.Windows.Application.RunDispatcher(object ignore) Unknown
PresentationFramework.dll!System.Windows.Application.RunInternal(System.Windows.Window window) Unknown

The specific answer to this issue will require seeing the specific code responsible. It likely is not an issue with a single table beyond the relationships that table has defined within the DbContext and database schema, and the current state of what the DbContext is tracking. (And what the Database might be locking, though that is usually a more intermittent type of problem)
Some things to check:
In your App example, you appear to be getting a fresh instance of the DbContext and disposing it. (Good) Does the 11s time reflect the Find+Save, or just Save? The very first query that a DbContext executes in an application incurs a 1-off (think Static) spin-up cost to initialize the model. For a more accurate timing with a first run scenario, you could do something like:
Using d = GetSystemContext(True)
Dim dump = d.Sales.Any()
' Start timing here...
Dim sp = d.Find(Of SaleProduct)(66246)
sp.DiscountAmount += 1
d.SaveChanges()
' End timing here...
End Using
*Sorry, my VB.Net is sadly out of date.. :) In any case, using a quick operation against the DbContext like an Any() will incur the 1-off spin-up cost. Any operation after that should be a more pure representation of the time needed to load & save data.
In your problematic code, are DbContext's guaranteed to be short-lived like this? DbContexts that are alive longer accrue references to a number of entities and any time any entity is persisted, it will scour it's tree of entities to determine if any related ones may need to be updated. Short-lived, disposed DbContexts are the way to go.
Have you run a profiler against the database to capture the exact SQL being run? Your example SQL doesn't look like an EF query, and references a "Sales" table rather than "SalesProduct". Having a profiler running while debugging your EF application operations is invaluable for revealing stuff going on behind the scenes that you don't expect.
Other possibilities would really depend on the code in question, but a profiler combined with breakpoints will generally help spot issues. Is the delay confirmed to be just when DbContext.SaveChanges happens, or the whole save process? If it's something like from the time the user clicks a Save button, then a Profiler might reveal that your code is tripping a lot of lazy-load calls (loading data to check and update prior to saving) or loading unexpected data. (common issues I've seen are misplaced ToList() calls before filtering statements, usually because the devs want to do something that EF cannot translate and ToList() seems like a "fix") If the delay is just from SaveChanges then the profiler can confirm what Update statements and the like are being produced and how long they are taking to run.

In the end it seems that the error disappeared after a index rebuild. Even though I cant understand if it was an index issue, how come it worked flawlessly time and again via SSMS and EF without window. But for now its working just dandy. Thanks again for all posters, as you were extremely helpful in narrowing down and focusing.

Entity framework is slow , very slow
in production code you need to use c# SQL command

Related

Windows Forms crashes while updating DataGridView in UI thread from worker thread while scrolling vertically continuesly

I have a Windows Forms App as a Client (in VB.NET) and I have a DataGridView where I want to see in real time changes that took place in a table in a database. I have another Windows Forms App as a Server that compares every 5 seconds old and new state and post to the client through WCF.
At the client side I read new data in a background worker thread (in order to have a responsive UI) and I run a loop inside the worker thread of new rows. Then when I try to update DataGridView table in the main thread using DataGridView1.Invoke method while scrolling continuesly the vertical scrollbar it throws the following exception.
at System.Collections.Hashtable.HashtableEnumerator.MoveNext()
at Janus.Windows.GridEX.JNSA.a(GridEXRow )
at Janus.Windows.GridEX.GridEX.a(Graphics , Boolean )
at Janus.Windows.GridEX.GridEX.a(Graphics )
at Janus.Windows.GridEX.GridEX.t()
at Janus.Windows.GridEX.GridEX.set_FirstRow(Int32 value)
at Janus.Windows.GridEX.GridEX.OnScrollBarScroll(Int32 scrollCode)
at Janus.Windows.GridEX.ScrollableBase.a(Object , ScrollEventArgs )
at Janus.Windows.GridEX.EditControls.JNSBY.OnScroll(ScrollEventArgs e)
at Janus.Windows.GridEX.EditControls.JNSBY.a(Int32 , Int32 )
at System.Windows.Forms.Control.WmMouseMove(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at Client.mdlMain.Main(String[] args)
Here is my code
Private Delegate Sub addrowcallback(table As DataTable, addedRow As DataRow)
Private Sub Add(table As DataTable, addedRow As DataRow)
If Me.IsHandleCreated Or GridControl1.IsHandleCreated Then
If (GridControl1.InvokeRequired Or Me.InvokeRequired) Then
Dim d As New addrowcallback(AddressOf Add)
Me.Invoke(d, table, addedRow)
Else
Dim gridHandle As IntPtr = GridControl1.Handle
GridControl1.Invoke(New Action(Sub()
table.ImportRow(addedRow)
End Sub))
Application.DoEvents()
End If
End If
End Sub
The exception is not happening when I stop WCF Service and I keep scrolling continuesly.
Important note!
I have about 30.000 records and every 5 seconds I have to update about between 0 - 30. If I don't scroll I have no exception. The exception is only while scrolling and updating.
As you can see in my code I implement the following line in order to request specific handle of the control in the main thread:
Dim gridHandle As IntPtr = GridControl1.Handle

Full text search schedule throw an exception

I try to create schedule for full text search, but when I choose Schedules menu I see this message:
I don't know how it can be affected with further error. The error happens when I press ok button on my schedule settings window.
How can I fix this error or can I add schedule by a TSQL script?
===================================
Object reference not set to an instance of an object. (SqlManagerUI)
------------------------------ Program Location:
at
Microsoft.SqlServer.Management.SqlManagerUI.FullTextIndexPropertiesSchedule.btnNew_Click(Object
sender, EventArgs e) at
System.Windows.Forms.Control.OnClick(EventArgs e) at
System.Windows.Forms.Button.OnClick(EventArgs e) at
System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent) at
System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons
button, Int32 clicks) at
System.Windows.Forms.Control.WndProc(Message& m) at
System.Windows.Forms.ButtonBase.WndProc(Message& m) at
System.Windows.Forms.Button.WndProc(Message& m) at
System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message&
m) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr
hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at
System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at
System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr
dwComponentID, Int32 reason, Int32 pvLoopData) at
System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32
reason, ApplicationContext context) at
System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32
reason, ApplicationContext context) at
System.Windows.Forms.Application.RunDialog(Form form) at
System.Windows.Forms.Form.ShowDialog(IWin32Window owner) at
System.Windows.Forms.Form.ShowDialog() at
Microsoft.SqlServer.Management.SqlMgmt.RunningFormsTable.RunningFormsTableImpl.ThreadStarter.StartThread()
If you are using SQL Server Express edition, then Agent Job is not included.
Please, try upgrade to other editions(Standard, Enterprise etc..).

Application Crash issue in WPF application in MVVM architecture

Recently, we are facing crash issue's in our application(Not on regular basis, generally on the client side) and we are not able to track the reason for the error. Most of the time the error that we get from the log is something like this ..
Type : System.IndexOutOfRangeException, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Message : Index was outside the bounds of the array.
Source : mscorlib
Help link :
Data : System.Collections.ListDictionaryInternal
TargetSite : Void Add(T)
HResult : -2146233080
Stack Trace : at System.Collections.Generic.List`1.Add(T item)
System.ComponentModel.BackgroundWorker.OnRunWorkerCompleted(RunWorkerCompletedEventArgs e)
at System.ComponentModel.BackgroundWorker.AsyncOperationCompleted(Object arg)
at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
Also in order to handle the crash at the application level, we have written certain code in App.xaml.cs file i.e.
private void CurrentDomain_UnhandledException(object sender,
UnhandledExceptionEventArgs e)
{
try
{
var exception = (Exception) e.ExceptionObject;
ExceptionHandler.HandleException(exception);
WpfMessageBox.Show(LocalizationManager.GetValue("AppErrorUnhandledException").ToString(),
LocalizationManager.GetValue("AppErrorUnhandledException").ToString(),
WpfMessageBoxButtons.OK,
WpfMessageBoxIcon.Error);
}
Is there anything we need to do besides this in order to stop the application to crash suddenly?
Note: Our application is based on MVVM pattern, concept such as service facade, unity, service orchestration, MutiThreading(Use of Background for calling service async)
P.S: Normally as per the logs, we are getting this error while caching the data.
Your CurrentDomain_UnhandledException will handle exceptions from Dispatcher, the UI thread.
BackgroundWorker is another thread, any exception occurs in this thread is not handled by the Dispatcher, and your system crashes.
You should handle the IndexOutOfRangeException inside the correct thread, the background one.
ng-HT

0x88980406 SyncFlush() ...Is there a workaround?

I get this exception in my application.
I have found links discussing it on the web but nothing indicating how to track it down and/or workaround it.
Please do not reply with links from the internet.
Please reply with strategies of tracking the source.
Please reply with workarounds if you found them.
Source: PresentationCore
Message: Exception from HRESULT: 0x88980406
Stack Trace:
at System.Windows.Media.Composition.DUCE.Channel.SyncFlush()
at System.Windows.Interop.HwndTarget.UpdateWindowSettings(Boolean enableRenderTarget, Nullable`1 channelSet)
at System.Windows.Interop.HwndTarget.UpdateWindowPos(IntPtr lParam)
at System.Windows.Interop.HwndTarget.HandleMessage(WindowMessage msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Interop.HwndSource.HwndTargetFilterMessage(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, Int32 numArgs)
at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
This is old, but I will answer anyways, since I had the same issue that I just resolved.https://stackoverflow.com/a/18003004/1415307
Basically, my issue with this error came down to an outdated video card driver. After updating to the newest driver, the issue has been resolved.
In my case it turned out the application in question was already pressing up on memory limits of its specced hardware. Any time I added code that used a decent amount of memory this would crop up.
I ended up using a MemoryFailPoint mechanism when I implemented a feature that placed processing an image buffer on another thread.
https://learn.microsoft.com/en-us/dotnet/api/system.runtime.memoryfailpoint
First implementation did the trick but after many tries QA caused a OOM bomb.
So I implemented a MemoryFailPoint() with GC.Collect() loop (hackish I know...but sometimes...get er done).
The main things I learned were:
This is a really bad bug in WPF.
You only have to worry about it if you have truly consumed an inordinate amount of memory.
With Microsoft's excellent help, we just solved a SyncFlush problem that has plagued us for more than a year. It turns out that we were creating multimedia timers in native code, but we weren't freeing them every time. More specifically, we called timeBeginPeriod and timeEndPeriod, but we called begin more times than end, thus creating a resource leak. The WPF rendering thread needs to use those timers, but we exhausted a limited supply of them (perhaps 65k). The result was that the rendering thread stopped rendering and either hung or caused a crash. Watch out for timers!

wpf debugging xaml

As part of learning wpf I'm working through some MS 'lab' sample apps; The finished exercise looks right, but I'm hitting a NullReferenceException with "Source code unavailable" issue (exception detail below). It appears to be thrown after the main window is shown.
I suspect the issue is in the XAML, but the debugger isn't helping me as much as I'd like. I've put break points everywhere the NavigationService is called in code, and none are being hit before the exception occurs. The type that the page function(s) returns was changed from string to object as part of the exercise.
In a real project. there would likely be enough unit tests and checks in place to not get in this state, but as long as I am and as part of the exercise of learning wpf, it surely can't hurt to know how to debug better!
How can I debug something like this better?
<--- EDITED COMMENTS
#electronherder
The closest guess I can make is that there is a Frame in Window1 that is not hooked up correctly. The idea is that the Frame displays contact information about the currently selected contact in a ListBox; this is done in code as follows:
void ListItemSelected(object sender, SelectionChangedEventArgs args) {
// show first page function on the right hand side frame
var pageFunction = new ContactDetailPage1(false, lstBoxAllContacts.SelectedIndex);
pageFunction.Return += pageFunction0_Return;
Frame_RightPane.Navigate(pageFunction);
//update status bar
if (lstBoxAllContacts.SelectedItem != null) {
var contact = lstBoxAllContacts.SelectedItem as Contact;
statusBar.Text = contact.FirstName + " " + contact.LastName;
}
else {
statusBar.Text = "No contacts on file.";
}
}
Before Window1 exits the call to Show(), this method executes without crashing. It does have that call to do some navigation, which I do not fully understand but is copied from the lab exercise notes. The navigation is related to a different window called ContactDetailPage1, and here's how the lab notes explain things:
"We want to be able to display this page in two modes: Read and Edit. That way we can reuse the Read mode in the contact details frame, Frame_RightPane."
The event hookup (pageFunction.Return += pageFunction0_Return;) is also a bit suspect, since it is intentionally a no-op to keep the compiler happy. I put an assert inside it though, as you can see in the code below:
// This is the ContactDetailPage1 page function's return handler; merely a placeholder
// since the page is displayed in read mode and doesn't return anything.
private static void pageFunction0_Return(object sender, ReturnEventArgs<object> e) {
Debug.Assert(false, "We should never actually be here!");
}
Finally, here is the XAML from Window1 that covers the frame:
<!-- RHS Panel -->
<Frame Name="Frame_RightPane" Grid.Column="0" Grid.ColumnSpan="1" Grid.Row="0" Grid.RowSpan="1"
Margin="201,65,0,0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Height="Auto"/>
That's the best I can do here, but here is the link to the lab for anyone that really wants to understand it (http://windowsclient.net/downloads/folders/hands-on-labs/entry3719.aspx).
<--- END OF EDIT --->
Cheers,
Berryl
<-- exception -->
System.NullReferenceException was unhandled
Message="Object reference not set to an instance of an object." Source="mscorlib"
StackTrace:
at System.Object.GetType()
at MS.Internal.AppModel.ReturnEventSaver._Detach(PageFunctionBase pf)
at System.Windows.Navigation.NavigationService.HookupNewTree(Object newTree, NavigateInfo navInfo, Uri newUri)
at System.Windows.Navigation.NavigationService.OnBeforeSwitchContent(Object newBP, NavigateInfo navInfo, Uri newUri)
at System.Windows.Navigation.NavigationService.MS.Internal.AppModel.IContentContainer.OnContentReady(ContentType contentType, Object bp, Uri bpu, Object navState)
at System.Windows.Navigation.NavigationService.DoNavigate(Object bp, NavigationMode navFlags, Object navState)
at System.Windows.Navigation.NavigateQueueItem.Dispatch(Object obj)
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.DispatcherOperation.InvokeImpl()
at System.Threading.ExecutionContext.runTryCode(Object userData)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
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.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Boolean isSingleParameter)
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.TranslateAndDispatchMessage(MSG& msg)
at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
at System.Windows.Application.RunInternal(Window window)
at AddressBook.MyApp.Main() in C:\Users\Berryl\Documents\Visual Studio 2008\Projects\UI related\DEV007 Building WPF Applications\Source\CS\Ex1\Task1\AddressBook\obj\Debug\MyApp.g.cs:line 0
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
Did you rename any of the classes - like Window1.xaml? I have seen similar failures in WPF projects when I have renamed the window class and missed some references. They are a number of them in the project in generated code. If you search the entire project for the old name you should be able to find orphaned references that might be causing the null ref.

Resources