forked from dotnet/SqlClient
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SqlHelperTest.cs
55 lines (48 loc) · 2.18 KB
/
SqlHelperTest.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace Microsoft.Data.SqlClient.Tests
{
public class SqlHelperTest
{
private void TimeOutATask()
{
TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
AsyncHelper.WaitForCompletion(tcs.Task, 1); //Will time out as task uncompleted
tcs.SetException(new TimeoutException("Dummy timeout exception")); //Our task now completes with an error
}
private Exception UnwrapException(Exception e)
{
return e?.InnerException != null ? UnwrapException(e.InnerException) : e;
}
[Fact]
public void WaitForCompletion_DoesNotCreateUnobservedException()
{
var unobservedExceptionHappenedEvent = new AutoResetEvent(false);
Exception unhandledException = null;
EventHandler<UnobservedTaskExceptionEventArgs> handleUnobservedException =
(o, a) => { unhandledException = a.Exception; unobservedExceptionHappenedEvent.Set(); };
TaskScheduler.UnobservedTaskException += handleUnobservedException;
try
{
TimeOutATask(); //Create the task in another function so the task has no reference remaining
GC.Collect(); //Force collection of unobserved task
GC.WaitForPendingFinalizers();
bool unobservedExceptionHappend = unobservedExceptionHappenedEvent.WaitOne(1);
if (unobservedExceptionHappend) //Save doing string interpolation in the happy case
{
var e = UnwrapException(unhandledException);
Assert.False(true, $"Did not expect an unobserved exception, but found a {e?.GetType()} with message \"{e?.Message}\"");
}
}
finally
{
TaskScheduler.UnobservedTaskException -= handleUnobservedException;
}
}
}
}