//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// UserRTX.NET satellite library | Author: Sergei Y.Kitáev
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
using System;
using System.Threading.Tasks;
using System.Runtime.CompilerServices;

#if !WASM
namespace user_rtx { using u = user_rtx;
#else
namespace user_rtx.wasm { using u = user_rtx.wasm;
#endif

/// <summary>
/// Lock for asynchronous threads (with deterministic finalization)
/// </summary>
[u.sync_only_disposable]
public class AsyncLockAuto: u.DisposableSyncImpl<AsyncLockAuto> {
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

public u.AsyncMonitor Monitor { get; }

[u.async_local]
[MethodImpl( MethodImplOptions.NoInlining )]
internal AsyncLockAuto( u.AsyncMonitor monitor )
{
   (Monitor = monitor).InitializeAL();
   ValidateDisposable();
}

//--------------------------------------------------------------------------------------------------

/// <exception cref="InvalidOperationException" />
public async ValueTask<u.AsyncLockAuto> Acquire_A()
{
   await Monitor.Enter_A();
   return this;
}
/*
/// <exception cref="InvalidOperationException" />
public u.AsyncLockAuto SyncAcquire_A()
{
   Monitor.SyncEnter();
   return this;
}
*/
//==================================================================================================

protected override AsyncLockAuto DisposableSelf => this;

protected override void OnSyncDispose() =>
   Monitor.Exit();

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
} // AsyncLockAuto

} // user_rtx (.wasm)
