---
title: "Handle GPU device loss in a C# game"
url: https://recursiveai.org/onegame/cookbook/handle-gpu-device-loss/
description: "Handle GPU device loss in OneGame: save progress and quit, simulate the loss, and see why a desktop run exits with code 6."
version: "2.8.0"
---

# Handle GPU device loss in a C# game

**onegame** is a free, open-source game engine for .NET from Recursive AI. MIT or Apache-2.0, no editor required.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneGame.Host) · [GitHub](https://github.com/recursive-ai-oss/onegame) · [Docs](https://recursiveai.org/onegame/docs/) · [Download example (.zip)](https://recursiveai.org/onegame/cookbook/handle-gpu-device-loss/handle-gpu-device-loss.zip)

Save progress before quitting. The demo runs on Linux with Vulkan.

OneGame raises `DeviceLost` for loss reported by Vulkan, Metal, or WebGPU.

```shell
dotnet add package RecursiveAI.OneGame.Host
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
game.DeviceLost += loss =>
{
    var save = game.Storage
        .Autosave("device lost");
    if (!save.Ok)
        Console.Error.WriteLine(save.Detail);
    game.Platform.RequestQuit();
};
```

[The example](https://recursiveai.org/onegame/cookbook/handle-gpu-device-loss/handle-gpu-device-loss.zip) is the full program below: unzip it and `dotnet run`.

Subscribe once on your `GameInstance` (`game` above). The example subscribes on the first frame, then uses `game.SimulateDeviceLoss()` after a frame has been displayed. The handler writes an autosave before asking the game to quit.

## The full program

```csharp
using OneGame.Core;
using OneGame.Host;
using OneGame.UI;

return GameApp.Run(new Demo(!args.Contains("--no-handler")),
    ["--gpu", "required", "--frames", "120", "--data", "demo-save"]);

sealed class Demo(bool handleLoss) : GameDefinition
{
    private bool _subscribed;
    private bool _rehearsed;

    public override string Name => "Device loss demo";
    public override void RegisterEntities(EntityRegistry registry) { }
    public override void Setup(World world) { }
    public override void DefineScreens(ScreenSet screens) =>
        screens.Add("main", _ => Ui.Label("Device loss demo"));

    public override void OnEachFrame(GameInstance game)
    {
        if (!_subscribed && handleLoss)
        {
            _subscribed = true;
            RegisterLossHandler(game);
        }

        if (_rehearsed || game.PresentedFrames < 1)
            return;
        _rehearsed = true;
        Console.WriteLine($"Adapter: {game.AdapterName}");
        if (!game.SimulateDeviceLoss())
            throw new InvalidOperationException("No usable device to simulate loss on.");
    }

    private static void RegisterLossHandler(GameInstance game)
    {
        game.DeviceLost += loss =>
        {
            Console.WriteLine($"{loss.Backend}: {loss.Reason}");
            var save = game.Storage.Autosave("device lost");
            Console.WriteLine(save.Ok ? "Autosave written" : save.Detail);
            game.Platform.RequestQuit();
        };
    }
}
```

`dotnet run` showed this on an NVIDIA GeForce RTX 4070 with Vulkan. The autosave went to `demo-save/slot-auto-0.sav`, and the process exited with code `6`.

```text
Adapter: NVIDIA GeForce RTX 4070
Vulkan: Simulated
Autosave written
error: The graphics device was lost (Vulkan, Simulated, SimulateLoss): the device loss was simulated
```

On exit code `6`, a desktop launcher can restart the game and have the new run load the latest save with `game.Storage.LoadLatest()`.

The last line reports the lost device, not a failed save. If saving fails, the handler prints the save error instead of claiming progress was written.

## Variations

**Run without a handler.** In a POSIX shell, run the example with the handler switched off and print the process status:

```shell
dotnet run -- --no-handler
echo "$?"
```

```text
Adapter: NVIDIA GeForce RTX 4070
error: The graphics device was lost (Vulkan, Simulated, SimulateLoss): the device loss was simulated The game has no DeviceLost handler, so it closed.
6
```

**Give a stalled device a different timeout.** If you create the instance yourself, pass this option to `GameInstance.Create(definition, options)` for a device the engine creates:

```csharp
var options = new GameOptions
{
    DeviceLostTimeout = TimeSpan.FromSeconds(3)
};
```

Keep it above the longest GPU job your game can legitimately submit. `ONEGPU_DEVICE_LOST_TIMEOUT` overrides it if set. If you supply a device through `GameOptions.Device`, that device has its own timeout instead.

## Related recipes

- [Detect and test GPU device loss with OneGPU](https://recursiveai.org/onegpu/cookbook/detect-and-test-gpu-device-loss/): use the device-layer API when you own the renderer, rather than handling loss in a game.
- [Save slots and settings](https://recursiveai.org/onegame/cookbook/save-slots-and-settings/): choose how the game saves and loads progress.

## The short answer

Subscribe to `GameInstance.DeviceLost`, save what the player needs to resume, and call `game.Platform.RequestQuit()`. OneGame raises the event once on the game thread. Its `DeviceLostInfo` gives you the backend, reason, message, and the operation if one is known. Use `SimulateDeviceLoss()` on a running game with a device to rehearse the response. You don’t need to reset the driver.

## What is VK_ERROR_DEVICE_LOST?

[`VK_ERROR_DEVICE_LOST`](https://docs.vulkan.org/spec/latest/chapters/devsandqueues.html#devsandqueues-lost-device) is Vulkan’s report that a logical device was lost. It doesn’t by itself tell you why. OneGame stops drawing, presenting and reading back frames after loss; it doesn’t recreate the device or the renderers in the existing instance. A capture isn’t a way to save the last visible frame at that point: it needs the device. Game state, saves, and simulation aren’t tied to the lost graphics objects, so you can still save the world from the handler.

Not all losses begin with that explicit return code. `GameOptions.DeviceLostTimeout` is a separate setting for detecting a lack of GPU progress on backends that have a bounded wait. It is not a timer for how long the game may take to save, nor a way to interrupt a driver stuck inside Vulkan’s present call.

## Why does the game exit with code 6 after device loss?

Without a handler, OneGame asks to quit and `GameApp.Run` returns `ExitCodes.DeviceLost` (`6`). If the handler saves and ends the run, that run returns `6` too. A launcher can distinguish that status from a normal exit without scraping the text. It cannot tell from the status alone whether a save was made.

When the run ends in loss, `GameApp.DeviceLossExitGrace` defaults to five seconds for teardown. If the process is still alive when the grace expires, OneGame tries a bounded flush of its output, then exits with code `6` at the operating-system level. Finalizers and process-exit handlers won’t run on that path. Write the save in `DeviceLost`, before calling `RequestQuit`, not in late cleanup. A handler that keeps the run going doesn’t start this exit timer just by receiving the event.

## Can a game recover from GPU device loss without restarting the computer?

In OneGame, start a fresh game run and load the save instead of trying to repair the running instance. When the host starts another instance, it doesn’t reuse the lost device. Build fresh textures, buffers and other GPU objects; the save should describe the game world, not hold references to the old GPU objects.

If you deliberately start a second `GameApp.Run` in the same process, set `GameApp.DeviceLossExitGrace` to `Timeout.InfiniteTimeSpan` before the first run. That turns off the forced exit; it also means the process no longer has that protection against stuck teardown. For a separate-process restart, keep the default and let a launcher or the player start the new run.
