SharedResource
.SharedResource() constructs and shares resource for same key. Resource is disposed when all IHandle<Value> are disposed.
// .SharedResource()
IProvider<string, Semaphore> namedSemaphores = Providers.Func<string, Semaphore>(name => new Semaphore(1, 1));
IProvider<string, IHandle<Semaphore>> sharedNamedSemaphores = namedSemaphores.SharedResource();
// Create handles, each has to be disposed.
IHandle<Semaphore> handleX0 = sharedNamedSemaphores["X"];
IHandle<Semaphore> handleX1 = sharedNamedSemaphores["X"];
// Get same shared reference
Semaphore x0 = handleX0.Value;
Semaphore x1 = handleX1.Value;
// Print reference id
Console.WriteLine(RuntimeHelpers.GetHashCode(x0)); // 12345
Console.WriteLine(RuntimeHelpers.GetHashCode(x1)); // 12345
// Dispose handles
handleX0.Dispose();
handleX1.Dispose(); // <- Semaphore is disposed here.
Full Example
Full example
using System;
using System.Runtime.CompilerServices;
using System.Threading;
using Avalanche.Utilities.Provider;
class provider_sharedresource
{
public static void Run()
{
{
// <01>
// .SharedResource()
IProvider<string, Semaphore> namedSemaphores = Providers.Func<string, Semaphore>(name => new Semaphore(1, 1));
IProvider<string, IHandle<Semaphore>> sharedNamedSemaphores = namedSemaphores.SharedResource();
// Create handles, each has to be disposed.
IHandle<Semaphore> handleX0 = sharedNamedSemaphores["X"];
IHandle<Semaphore> handleX1 = sharedNamedSemaphores["X"];
// Get same shared reference
Semaphore x0 = handleX0.Value;
Semaphore x1 = handleX1.Value;
// Print reference id
Console.WriteLine(RuntimeHelpers.GetHashCode(x0)); // 12345
Console.WriteLine(RuntimeHelpers.GetHashCode(x1)); // 12345
// Dispose handles
handleX0.Dispose();
handleX1.Dispose(); // <- Semaphore is disposed here.
// </01>
}
}
}