6

I was stepping through the debugger in some website database code, and ended execution before the database changes were applied. But they were still written to the database!

I tried to recreate the problem using a Windows Form application, and it didn't write to the database (expected behaviour). I went back to the website, and it did.

Here is a simple example page. I am running this in a web site if it makes a difference:

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Diagnostics" %>

<!DOCTYPE html>

<script runat="server">

    protected void Page_Load(object sender, EventArgs e)
    {
        using (MsSqlDataContextDataContext db = new MsSqlDataContextDataContext())
        {
            Product product = db.Products.First(p => p.id == 21);
            Debug.WriteLine("Line 1");
            // I learnt the hard way that if you try to update the database with the value
            // that already exists, it seems to get optimised away.
            // The update must a new value. 
            product.Type = "bogus" + DateTime.UtcNow.Ticks;
            Debug.WriteLine("Line 2");  // <- Breakpoint here
            db.SubmitChanges();
        }
    }
</script>

<html>
<head runat="server">
</head>
</html>

I end execution (Shift+F5) at the breakpoint, before the second debug print or SubmitChanges() get executed. "Line 2" is not output to the debug window, but the database changes are made.

Running the same test in a Windows Form does behave the same.

Is the page life-cycle, or session management somehow interfering here? How is this even possible, Line 2 doesn't get printed!

Ian
  • 1,475
  • 2
  • 15
  • 31
  • Are you getting an error/exception on windows form, how does it not work? – raidensan Apr 29 '16 at 06:08
  • @raidensan I'll reword it. It does not behave the same. It does not write the change to the database (as I expected it should not, given I aborted before the `Submit` call). – Ian Apr 29 '16 at 06:09
  • Do "throw new Exception()" instead of "Debug.WriteLine("Line 2")" in your example and see how it goes. – Evk Apr 29 '16 at 06:15

1 Answers1

6

When you stop debugging in the winform app, the process is terminating and your code stops executing.

In asp.net this is not the case. When you stop the debugger (usually) it won't terminate the iis process, just detach the debugger. Your code continues running and the request completes.

There are duplicates for this question, have no rep to mark this as duplicate.

apr
  • 552
  • 3
  • 9
  • Good explanation, I did search but not knowing the cause makes it difficult. I'll see if I can find a dupe and flag it myself :) Or link me a dupe and I'll flag it. – Ian Apr 29 '16 at 06:29
  • Not an exact duplicate: [link](http://stackoverflow.com/questions/1338785/the-asp-net-code-still-executes-after-clicking-stopping-debugging-in-vs2008) (Explains you need to terminate the process) – apr Apr 29 '16 at 07:12