-
-
Notifications
You must be signed in to change notification settings - Fork 389
/
BusyHelper.cs
56 lines (49 loc) · 1.56 KB
/
BusyHelper.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
56
//-----------------------------------------------------------------------
// <copyright file="INotifyBusy.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: https://cslanet.com
// </copyright>
// <summary>Interface defining an object that notifies when it</summary>
//-----------------------------------------------------------------------
using System.Runtime.CompilerServices;
namespace Csla.Core {
/// <summary>
/// Helper class for busy related functionality spread across different business type implementations.
/// </summary>
internal static class BusyHelper
{
public static async Task WaitForIdle(INotifyBusy source, TimeSpan timeout, [CallerMemberName] string methodName = "")
{
if (!source.IsBusy)
{
return;
}
var tcs = new TaskCompletionSource<object>();
try
{
source.BusyChanged += ObserverForIsBusyChange;
if (!source.IsBusy)
{
return;
}
var timeoutTask = Task.Delay(timeout);
var finishedTask = await Task.WhenAny(tcs.Task, timeoutTask).ConfigureAwait(false);
if (finishedTask == timeoutTask)
{
throw new TimeoutException($"{source.GetType().FullName}.{methodName} - {timeout}.");
}
}
finally
{
source.BusyChanged -= ObserverForIsBusyChange;
}
void ObserverForIsBusyChange(object sender, BusyChangedEventArgs e)
{
if (!source.IsBusy && !e.Busy)
{
tcs.TrySetResult(null);
}
}
}
}
}