forked from reactiveui/ReactiveUI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMessageBusExtensions.cs
More file actions
78 lines (69 loc) · 2.5 KB
/
MessageBusExtensions.cs
File metadata and controls
78 lines (69 loc) · 2.5 KB
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// Copyright (c) 2022 .NET Foundation and Contributors. All rights reserved.
// 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 full license information.
using System;
using System.Reactive.Disposables;
using System.Threading;
namespace ReactiveUI.Testing;
/// <summary>
/// Message bus testing extensions.
/// </summary>
public static class MessageBusExtensions
{
private static readonly object mbGate = 42;
/// <summary>
/// Override the default Message Bus during the specified block.
/// </summary>
/// <typeparam name="TRet">The return type.</typeparam>
/// <param name="messageBus">The message bus to use for the block.</param>
/// <param name="block">The function to execute.</param>
/// <returns>The return value of the function.</returns>
public static TRet With<TRet>(this IMessageBus messageBus, Func<TRet> block)
{
if (block is null)
{
throw new ArgumentNullException(nameof(block));
}
using (messageBus.WithMessageBus())
{
return block();
}
}
/// <summary>
/// WithMessageBus allows you to override the default Message Bus
/// implementation until the object returned is disposed. If a
/// message bus is not specified, a default empty one is created.
/// </summary>
/// <param name="messageBus">The message bus to use, or null to create
/// a new one using the default implementation.</param>
/// <returns>An object that when disposed, restores the original
/// message bus.</returns>
public static IDisposable WithMessageBus(this IMessageBus messageBus)
{
var origMessageBus = MessageBus.Current;
Monitor.Enter(mbGate);
MessageBus.Current = messageBus;
return Disposable.Create(() =>
{
MessageBus.Current = origMessageBus;
Monitor.Exit(mbGate);
});
}
/// <summary>
/// Override the default Message Bus during the specified block.
/// </summary>
/// <param name="messageBus">The message bus to use for the block.</param>
/// <param name="block">The action to execute.</param>
public static void With(this IMessageBus messageBus, Action block)
{
if (block is null)
{
throw new ArgumentNullException(nameof(block));
}
using (messageBus.WithMessageBus())
{
block();
}
}
}