LibUv Networking (#65)

This commit is contained in:
Kamron Batman 2019-12-26 18:08:50 -08:00 • committed by GitHub
parent ec6629fbe9
commit 5e2be2d7b6
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
69 changed files with 5612 additions and 586 deletions

View file

@ -0,0 +1,72 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Diagnostics;
using System.Threading;
namespace Libuv.Internal
{
public class UvAsyncHandle : UvHandle
{
private static readonly LibuvFunctions.uv_close_cb _destroyMemory = handle => DestroyMemory(handle);
private static readonly LibuvFunctions.uv_async_cb _uv_async_cb = handle => AsyncCb(handle);
private Action _callback;
private Action<Action<IntPtr>, IntPtr> _queueCloseHandle;
public UvAsyncHandle(ILibuvTrace logger) : base(logger)
{
}
public void Init(UvLoopHandle loop, Action callback, Action<Action<IntPtr>, IntPtr> queueCloseHandle)
{
CreateMemory(
loop.Libuv,
loop.ThreadId,
loop.Libuv.handle_size(LibuvFunctions.HandleType.ASYNC));
_callback = callback;
_queueCloseHandle = queueCloseHandle;
_uv.async_init(loop, this, _uv_async_cb);
}
public void Send()
{
_uv.async_send(this);
}
private static void AsyncCb(IntPtr handle)
{
FromIntPtr<UvAsyncHandle>(handle)._callback.Invoke();
}
protected override bool ReleaseHandle()
{
var memory = handle;
if (memory != IntPtr.Zero)
{
handle = IntPtr.Zero;
if (Thread.CurrentThread.ManagedThreadId == ThreadId)
{
_uv.close(memory, _destroyMemory);
}
else if (_queueCloseHandle != null)
{
// This can be called from the finalizer.
// Ensure the closure doesn't reference "this".
LibuvFunctions uv = _uv;
_queueCloseHandle(memory2 => uv.close(memory2, _destroyMemory), memory);
uv.unsafe_async_send(memory);
}
else
{
Debug.Assert(false, "UvAsyncHandle not initialized with queueCloseHandle action");
return false;
}
}
return true;
}
}
}