Experience
Projects
My Stack
Case studies
Contact me
Open my CV

·5 min read

TaskPad hot exit: debounced backups, an atomic session file, splits as text

Closing a text editor with unsaved work should never open a dialog. That was the rule I set for TaskPad, a WPF task editor, when I added session restore: close the app, reopen it, and every window, split, tab, cursor position and unsaved line is back. The interesting part was not the idea. It was the handful of decisions that keep it from losing the very text it exists to protect.

Project
TaskPad
Date
Oct 2026
Stack
C#, WPF
Commit
15a5c06

What gets written, and when

The class comment calls it hot exit: it "remembers every window, split layout, tab and cursor, and keeps unsaved / untitled text in session\backup-*.txt". The text must survive a crash and a power cut as well as a clean quit, so saving cannot wait for the close event. Every edit or tab change calls MarkDirty, which restarts a two second timer:

csharp
public static void MarkDirty()
{
    if (!Enabled || _restoring || Quitting) return;
    if (_timer == null)
    {
        _timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(2) };
        _timer.Tick += (s, e) => { _timer.Stop(); if (Workspace.Windows.Count > 0) Save(); };
    }
    _timer.Stop();
    _timer.Start();
}

Restarting the timer on each call turns a burst of typing into one save after the pause, so the editor does not write files on every keystroke. The two guards matter too. While restoring, the editor raises exactly the events that would mark the session dirty, and saving in the middle of a restore would overwrite the session with a half-built one. Quitting does the same job during a shutdown or an update restart.

One file for structure, one per document for text

Save walks Workspace.Docs. A document gets a backup file only when it needs one: untitled with any text, or a file on disk with unsaved changes. A clean saved file is just a path.

csharp
if (doc.Path == null ? doc.Document.TextLength > 0 : doc.Dirty)
{
    backup = $"backup-{id}.txt";
    File.WriteAllText(Path.Combine(Dir, backup), doc.Document.Text, new UTF8Encoding(false));
    keep.Add(backup);
}

The session file itself is plain text. Each line is tab-separated with every field passed through Uri.EscapeDataString, so a path or an untitled name containing a tab, a newline or a semicolon cannot break the format. The first line is a version string, taskpad-session 1, and Restore returns false on any other header, so a future format change cannot be misread by an old build. Lines are doc, win and grp records, and a tab entry is docId,caret,scroll.

The two details that protect the text

The first is how the file is written:

csharp
var tmp = File_ + ".tmp";
File.WriteAllText(tmp, sb.ToString(), new UTF8Encoding(false));
if (File.Exists(File_)) File.Replace(tmp, File_, null); else File.Move(tmp, File_);
foreach (var f in Directory.GetFiles(Dir, "backup-*.txt"))
    if (!keep.Contains(Path.GetFileName(f))) try { File.Delete(f); } catch { }

If the process dies halfway through writing, a direct overwrite would leave a truncated session file and the next start would restore nothing. Writing to session.txt.tmp and swapping means the old complete file stays valid until the new complete one replaces it. The order of the last two lines is deliberate as well. Backups the new session no longer references are deleted only after the new session file is in place, so there is no moment where the session points at a backup that is gone.

The second is the close path in TaskWindow.OnClosing. When the last window closes, or an update restarts the app, files with a path and unsaved changes are saved to disk, untitled text stays in the backup, and nothing prompts. Closing one of several windows still asks, because that window's documents will not be in the next session's last-window snapshot if the user discards them:

csharp
bool hotExit = Session.Enabled && (Session.Quitting || Workspace.Windows.Count == 1);
foreach (var t in tabs)
{
    if (!t.Doc.Views.All(v => v.Group?.Owner == this)) continue;
    if (hotExit) { if (t.Doc.Path != null && t.Doc.Dirty) t.Doc.Save(this, false); }
    else if (!t.Doc.ConfirmClose(this)) { e.Cancel = true; return; }
}

A document shown in more than one window is skipped by the All check, since another view still owns it.

Saving a split layout as text

A window can be split into groups of tabs, nested to any depth. I did not want a serializer for a tree of WPF Grid elements, so LayoutSpec writes the tree as a string. Groups are numbered in the order the window lists them, and a split is (H ...) or (V ...):

code
(H 0 (V 1 2))

That reads as group 0 on the left and, to its right, groups 1 and 2 stacked. ApplyLayout is a small recursive parser for exactly this grammar. If anything in it throws, it clears what it built and falls back to a single empty group, so a corrupt layout string costs the split arrangement and not the tabs. The grp lines then fill the groups in order.

What the code also shows

Save wraps its whole body in an empty catch { }. For a background save that must never crash the editor, I decided that was acceptable, but it has a cost I should state plainly: if writing the session ever fails, nothing tells the user, and the next start restores an older session. Restore is defensive in the same way. It drops documents no window shows, closes windows whose files were all deleted since last time, and clamps the caret to the current text length.

What I took from it

Hot exit looks like a feature about closing. In the code it is a feature about writes: when they happen, which ones are atomic, and the order in which old data is deleted. The format and the layout string are small. The ordering of a temp file, a replace and a cleanup is what makes the promise in the README, that nothing is lost on close, true after a crash too.

#csharp#wpf#persistence#editor#reliability

Keep reading

Have a project in mind?