Skip to content

Commit 4c2929f

Browse files
Add note about async main in .NET (#4895)
1 parent 8ae4f25 commit 4c2929f

File tree

1 file changed

+52
-1
lines changed

1 file changed

+52
-1
lines changed

src/platforms/dotnet/common/troubleshooting.mdx

Lines changed: 52 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,57 @@ description: "Learn more about how to troubleshoot common issues with the .NET S
99
If you're using a proxy server that relies on `X-Forwarded-For`, you might need to [configure ASP.NET Core
1010
so that it's aware of it](https://docs.microsoft.com/aspnet/core/host-and-deploy/proxy-load-balancer).
1111

12-
See [this GitHub issue] (https://github.com/getsentry/sentry-dotnet/issues/258) for more context.
12+
See [this GitHub issue](https://github.com/getsentry/sentry-dotnet/issues/258) for more context.
13+
14+
## Unhandled exceptions are not captured when using an async `Main` method
15+
16+
Starting with C# 7.1, a program's [`Main` method](https://docs.microsoft.com/dotnet/csharp/fundamentals/program-structure/main-command-line) can be declared either synchronously or asynchronously. However, the asynchronous approach is not fully compatible with the Sentry SDK. If your application uses an async `Main` method, the Sentry SDK will be disposed before an unhandled exception can be captured.
17+
18+
In other words, this is insufficient:
19+
20+
```csharp
21+
static async Task Main()
22+
{
23+
using var _ = SentrySdk.Init(o => { /* your options */ });
24+
await DoSomethingAsync(); // an unhandled exception here will not be captured by Sentry
25+
}
26+
```
27+
28+
There are two different ways to work around this issue:
29+
30+
- You can avoid unhandled exceptions by wrapping your code in a try/catch block:
31+
```csharp
32+
static async Task Main()
33+
{
34+
using var _ = SentrySdk.Init(o => { /* your options */ });
35+
try
36+
{
37+
await DoSomethingAsync();
38+
}
39+
catch (Exception ex)
40+
{
41+
SentrySdk.CaptureException(ex);
42+
}
43+
}
44+
```
45+
46+
- You can use a synchronous `Main` method to ensure the Sentry SDK isn't disposed prematurely:
47+
48+
```csharp
49+
static void Main()
50+
{
51+
using var _ = SentrySdk.Init(o => { /* your options */ });
52+
MainAsync().GetAwaiter().GetResult();
53+
}
54+
55+
static async Task MainAsync()
56+
{
57+
await DoSomethingAsync();
58+
}
59+
```
60+
61+
Note that with this approach, it is not advised to use `.Wait()` or `.Result`, as that would wrap unhandled exceptions in an `AggregateException`.
62+
63+
See [this GitHub issue](https://github.com/getsentry/sentry-dotnet/issues/321) for more context.
1364

1465
<PlatformContent includePath="troubleshooting" />

0 commit comments

Comments
 (0)