Here are the examples of the csharp api System.Threading.SemaphoreSlim.Release() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
2025 Examples
19
View Source File : AsyncLock.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
public void Dispose()
{
#if DEBUG
Debug.replacedert(!_disposed);
_disposed = true;
#endif
lock (_parent._reentrancy)
{
Interlocked.Decrement(ref _parent._reentrances);
if (_parent._reentrances == 0)
{
//the owning thread is always the same so long as we are in a nested stack call
//we reset the owning id to null only when the lock is fully unlocked
_parent._owningId = UnlockedThreadId;
if (_parent._retry.CurrentCount == 0)
{
_parent._retry.Release();
}
}
}
}
19
View Source File : BaseDapper.Async.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
protected async Task<TReturn> CommandExecuteAsync<TReturn>(bool? enableCache, Func<Task<TReturn>> execQuery, string sql, object param, string cacheKey, TimeSpan? expire, int? pageIndex = default, int? pageSize = default)
{
if (!IsEnableCache(enableCache))
return await execQuery();
cacheKey = CacheKeyBuilder.Generate(sql, param, cacheKey, pageIndex, pageSize);
Logger.LogDebug("Get query results from cache.");
var cache = Cache.TryGet<TReturn>(cacheKey);
if (cache.ExistKey)
{
Logger.LogDebug("Get value from cache successfully.");
return cache.Value;
}
Logger.LogDebug("The cache does not exist, acquire a lock, queue to query data from the database.");
await SemapreplacedSlim.Value.WaitAsync(TimeSpan.FromSeconds(5));
try
{
Logger.LogDebug("The lock has been acquired, try again to get the value from the cache.");
var cacheResult = Cache.TryGet<TReturn>(cacheKey);
if (cacheResult.ExistKey)
{
Logger.LogDebug("Try again, get value from cache successfully.");
return cacheResult.Value;
}
Logger.LogDebug("Try again, still fail to get the value from the cache, start to get the value from the data.");
var result = await execQuery();
Cache.TrySet(cacheKey, result, expire ?? CacheConfiguration.Expire);
Logger.LogDebug("Get value from data and write to cache.");
return result;
}
finally
{
Logger.LogDebug("Release lock.");
SemapreplacedSlim.Value.Release();
}
}
19
View Source File : PkgChecker.cs
License : MIT License
Project Creator : 13xforever
License : MIT License
Project Creator : 13xforever
private static void Write(string str, ConsoleColor? color = null)
{
Sync.Wait();
try
{
if (color is ConsoleColor c)
Console.ForegroundColor = c;
Console.Write(str);
if (color.HasValue)
Console.ResetColor();
}
finally
{
Sync.Release();
}
}
19
View Source File : B2CAuthService.cs
License : MIT License
Project Creator : 1iveowl
License : MIT License
Project Creator : 1iveowl
private async Task<T> ExecuteSynchronously<T>(Func<Task<T>> task)
{
await _semapreplaced.WaitAsync().ConfigureAwait(false);
try
{
return await task();
}
finally
{
_semapreplaced.Release();
}
}
19
View Source File : B2CAuthService.cs
License : MIT License
Project Creator : 1iveowl
License : MIT License
Project Creator : 1iveowl
private async Task ExecuteSynchronously(Func<Task> task)
{
await _semapreplaced.WaitAsync().ConfigureAwait(false);
try
{
await task();
}
finally
{
_semapreplaced.Release();
}
}
19
View Source File : RecordStream.cs
License : MIT License
Project Creator : a1q123456
License : MIT License
Project Creator : a1q123456
private async Task SeekAndPlay(double milliSeconds, CancellationToken ct)
{
await _playLock.WaitAsync();
Interlocked.Exchange(ref _playing, 1);
try
{
_recordFile.Seek(9, SeekOrigin.Begin);
FlvDemuxer.SeekNoLock(milliSeconds, _metaData == null ? null : _metaData.Data[2] as Dictionary<string, object>, ct);
await StartPlayNoLock(ct);
}
catch (Exception e)
{
Console.WriteLine(e);
}
finally
{
Interlocked.Exchange(ref _playing, 0);
_playLock.Release();
}
}
19
View Source File : WebSocketPlayController.cs
License : MIT License
Project Creator : a1q123456
License : MIT License
Project Creator : a1q123456
private async Task PlayRecordFile()
{
Interlocked.Exchange(ref _playing, 1);
var buffer = new byte[512];
int bytesRead;
do
{
await _playLock.WaitAsync();
bytesRead = await _recordFile.ReadAsync(buffer);
await Session.SendRawDataAsync(buffer);
_playLock.Release();
if (_playRangeTo < _recordFile.Position && _playRangeTo != -1)
{
break;
}
} while (bytesRead != 0);
Interlocked.Exchange(ref _playing, 0);
}
19
View Source File : IOPipeLine.cs
License : MIT License
Project Creator : a1q123456
License : MIT License
Project Creator : a1q123456
internal async Task SendRawData(ReadOnlyMemory<byte> data)
{
var tcs = new TaskCompletionSource<int>();
var buffer = _arrayPool.Rent(data.Length);
data.CopyTo(buffer);
_writerQueue.Enqueue(new WriteState()
{
Buffer = buffer,
TaskSource = tcs,
Length = data.Length
});
_writerSignal.Release();
await tcs.Task;
}
19
View Source File : ChunkStreamContext.cs
License : MIT License
Project Creator : a1q123456
License : MIT License
Project Creator : a1q123456
internal async Task MultiplexMessageAsync(uint chunkStreamId, Message message)
{
if (!message.MessageHeader.MessageStreamId.HasValue)
{
throw new InvalidOperationException("cannot send message that has not attached to a message stream");
}
byte[] buffer = null;
uint length = 0;
using (var writeBuffer = new ByteBuffer())
{
var context = new Serialization.SerializationContext()
{
Amf0Reader = _amf0Reader,
Amf0Writer = _amf0Writer,
Amf3Reader = _amf3Reader,
Amf3Writer = _amf3Writer,
WriteBuffer = writeBuffer
};
message.Serialize(context);
length = (uint)writeBuffer.Length;
Debug.replacedert(length != 0);
buffer = _arrayPool.Rent((int)length);
writeBuffer.TakeOutMemory(buffer);
}
try
{
message.MessageHeader.MessageLength = length;
Debug.replacedert(message.MessageHeader.MessageLength != 0);
if (message.MessageHeader.MessageType == 0)
{
message.MessageHeader.MessageType = message.GetType().GetCustomAttribute<RtmpMessageAttribute>().MessageTypes.First();
}
Debug.replacedert(message.MessageHeader.MessageType != 0);
Task ret = null;
// chunking
bool isFirstChunk = true;
_rtmpSession.replacedertStreamId(message.MessageHeader.MessageStreamId.Value);
for (int i = 0; i < message.MessageHeader.MessageLength;)
{
_previousWriteMessageHeader.TryGetValue(chunkStreamId, out var prevHeader);
var chunkHeaderType = SelectChunkType(message.MessageHeader, prevHeader, isFirstChunk);
isFirstChunk = false;
GenerateBasicHeader(chunkHeaderType, chunkStreamId, out var basicHeader, out var basicHeaderLength);
GenerateMesesageHeader(chunkHeaderType, message.MessageHeader, prevHeader, out var messageHeader, out var messageHeaderLength);
_previousWriteMessageHeader[chunkStreamId] = (MessageHeader)message.MessageHeader.Clone();
var headerLength = basicHeaderLength + messageHeaderLength;
var bodySize = (int)(length - i >= _writeChunkSize ? _writeChunkSize : length - i);
var chunkBuffer = _arrayPool.Rent(headerLength + bodySize);
await _sync.WaitAsync();
try
{
basicHeader.replacedpan(0, basicHeaderLength).CopyTo(chunkBuffer);
messageHeader.replacedpan(0, messageHeaderLength).CopyTo(chunkBuffer.replacedpan(basicHeaderLength));
_arrayPool.Return(basicHeader);
_arrayPool.Return(messageHeader);
buffer.replacedpan(i, bodySize).CopyTo(chunkBuffer.replacedpan(headerLength));
i += bodySize;
var isLastChunk = message.MessageHeader.MessageLength - i == 0;
long offset = 0;
long totalLength = headerLength + bodySize;
long currentSendSize = totalLength;
while (offset != (headerLength + bodySize))
{
if (WriteWindowAcknowledgementSize.HasValue && Interlocked.Read(ref WriteUnAcknowledgedSize) + headerLength + bodySize > WriteWindowAcknowledgementSize.Value)
{
currentSendSize = Math.Min(WriteWindowAcknowledgementSize.Value, currentSendSize);
//var delayCount = 0;
while (currentSendSize + Interlocked.Read(ref WriteUnAcknowledgedSize) >= WriteWindowAcknowledgementSize.Value)
{
await Task.Delay(1);
}
}
var tsk = _ioPipeline.SendRawData(chunkBuffer.AsMemory((int)offset, (int)currentSendSize));
offset += currentSendSize;
totalLength -= currentSendSize;
if (WriteWindowAcknowledgementSize.HasValue)
{
Interlocked.Add(ref WriteUnAcknowledgedSize, currentSendSize);
}
if (isLastChunk)
{
ret = tsk;
}
}
if (isLastChunk)
{
if (message.MessageHeader.MessageType == MessageType.SetChunkSize)
{
var setChunkSize = message as SetChunkSizeMessage;
_writeChunkSize = setChunkSize.ChunkSize;
}
else if (message.MessageHeader.MessageType == MessageType.SetPeerBandwidth)
{
var m = message as SetPeerBandwidthMessage;
ReadWindowAcknowledgementSize = m.WindowSize;
}
else if (message.MessageHeader.MessageType == MessageType.WindowAcknowledgementSize)
{
var m = message as WindowAcknowledgementSizeMessage;
WriteWindowAcknowledgementSize = m.WindowSize;
}
}
}
finally
{
_sync.Release();
_arrayPool.Return(chunkBuffer);
}
}
Debug.replacedert(ret != null);
await ret;
}
finally
{
_arrayPool.Return(buffer);
}
}
19
View Source File : RunnerL0.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Runner")]
//process 2 new job messages, and one cancel message
public async void TestRunAsync()
{
using (var hc = new TestHostContext(this))
{
//Arrange
var runner = new Runner.Listener.Runner();
hc.SetSingleton<IConfigurationManager>(_configurationManager.Object);
hc.SetSingleton<IJobNotification>(_jobNotification.Object);
hc.SetSingleton<IMessageListener>(_messageListener.Object);
hc.SetSingleton<IPromptManager>(_promptManager.Object);
hc.SetSingleton<IRunnerServer>(_runnerServer.Object);
hc.SetSingleton<IConfigurationStore>(_configStore.Object);
runner.Initialize(hc);
var settings = new RunnerSettings
{
PoolId = 43242
};
var message = new TaskAgentMessage()
{
Body = JsonUtility.ToString(CreateJobRequestMessage("job1")),
MessageId = 4234,
MessageType = JobRequestMessageTypes.PipelineAgentJobRequest
};
var messages = new Queue<TaskAgentMessage>();
messages.Enqueue(message);
var signalWorkerComplete = new SemapreplacedSlim(0, 1);
_configurationManager.Setup(x => x.LoadSettings())
.Returns(settings);
_configurationManager.Setup(x => x.IsConfigured())
.Returns(true);
_messageListener.Setup(x => x.CreateSessionAsync(It.IsAny<CancellationToken>()))
.Returns(Task.FromResult<bool>(true));
_messageListener.Setup(x => x.GetNextMessageAsync(It.IsAny<CancellationToken>()))
.Returns(async () =>
{
if (0 == messages.Count)
{
signalWorkerComplete.Release();
await Task.Delay(2000, hc.RunnerShutdownToken);
}
return messages.Dequeue();
});
_messageListener.Setup(x => x.DeleteSessionAsync())
.Returns(Task.CompletedTask);
_messageListener.Setup(x => x.DeleteMessageAsync(It.IsAny<TaskAgentMessage>()))
.Returns(Task.CompletedTask);
_jobDispatcher.Setup(x => x.Run(It.IsAny<Pipelines.AgentJobRequestMessage>(), It.IsAny<bool>()))
.Callback(() =>
{
});
_jobNotification.Setup(x => x.StartClient(It.IsAny<String>()))
.Callback(() =>
{
});
hc.EnqueueInstance<IJobDispatcher>(_jobDispatcher.Object);
_configStore.Setup(x => x.IsServiceConfigured()).Returns(false);
//Act
var command = new CommandSettings(hc, new string[] { "run" });
Task runnerTask = runner.ExecuteCommand(command);
//replacedert
//wait for the runner to run one job
if (!await signalWorkerComplete.WaitAsync(2000))
{
replacedert.True(false, $"{nameof(_messageListener.Object.GetNextMessageAsync)} was not invoked.");
}
else
{
//Act
hc.ShutdownRunner(ShutdownReason.UserCancelled); //stop Runner
//replacedert
Task[] taskToWait2 = { runnerTask, Task.Delay(2000) };
//wait for the runner to exit
await Task.WhenAny(taskToWait2);
replacedert.True(runnerTask.IsCompleted, $"{nameof(runner.ExecuteCommand)} timed out.");
replacedert.True(!runnerTask.IsFaulted, runnerTask.Exception?.ToString());
replacedert.True(runnerTask.IsCanceled);
_jobDispatcher.Verify(x => x.Run(It.IsAny<Pipelines.AgentJobRequestMessage>(), It.IsAny<bool>()), Times.Once(),
$"{nameof(_jobDispatcher.Object.Run)} was not invoked.");
_messageListener.Verify(x => x.GetNextMessageAsync(It.IsAny<CancellationToken>()), Times.AtLeastOnce());
_messageListener.Verify(x => x.CreateSessionAsync(It.IsAny<CancellationToken>()), Times.Once());
_messageListener.Verify(x => x.DeleteSessionAsync(), Times.Once());
_messageListener.Verify(x => x.DeleteMessageAsync(It.IsAny<TaskAgentMessage>()), Times.AtLeastOnce());
// verify that we didn't try to delete local settings file (since we're not ephemeral)
_configurationManager.Verify(x => x.DeleteLocalRunnerConfig(), Times.Never());
}
}
}
19
View Source File : AsyncLock.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public void Dispose()
{
m_toRelease.m_semapreplaced.Release();
}
19
View Source File : AsyncLock.cs
License : MIT License
Project Creator : ad313
License : MIT License
Project Creator : ad313
public void Dispose()
=> _toRelease._semapreplaced.Release();
19
View Source File : TargetCollection.cs
License : Apache License 2.0
Project Creator : adamralph
License : Apache License 2.0
Project Creator : adamralph
private async Task RunAsync(
Target target,
List<Target> explicitTargets,
bool dryRun,
bool parallel,
bool skipDependencies,
Func<Exception, bool> messageOnly,
Output output,
Dictionary<Target, Task> runningTargets,
SemapreplacedSlim sync,
Queue<Target> dependencyPath)
{
if (output.Verbose)
{
// can switch to ImmutableQueue after moving to .NET 5+
dependencyPath = new Queue<Target>(dependencyPath);
dependencyPath.Enqueue(target);
}
bool targetWasAlreadyStarted;
Task runningTarget;
// cannot use WaitAsync() as it is not reentrant
#pragma warning disable CA1849 // Call async methods when in an async method
sync.Wait();
#pragma warning restore CA1849 // Call async methods when in an async method
try
{
targetWasAlreadyStarted = runningTargets.TryGetValue(target, out runningTarget);
}
finally
{
_ = sync.Release();
}
if (targetWasAlreadyStarted)
{
if (runningTarget.IsAwaitable())
{
await output.Awaiting(target, dependencyPath).Tax();
await runningTarget.Tax();
}
return;
}
await output.WalkingDependencies(target, dependencyPath).Tax();
if (parallel)
{
var tasks = target.Dependencies.Select(RunDependencyAsync);
await Task.WhenAll(tasks).Tax();
}
else
{
foreach (var dependency in target.Dependencies)
{
await RunDependencyAsync(dependency).Tax();
}
}
async Task RunDependencyAsync(string dependency)
{
if (!this.Contains(dependency))
{
await output.IgnoringNonExistentDependency(target, dependency, dependencyPath).Tax();
}
else
{
await this.RunAsync(this[dependency], explicitTargets, dryRun, false, skipDependencies, messageOnly, output, runningTargets, sync, dependencyPath).Tax();
}
}
if (!skipDependencies || explicitTargets.Contains(target))
{
// cannot use WaitAsync() as it is not reentrant
#pragma warning disable CA1849 // Call async methods when in an async method
sync.Wait();
#pragma warning restore CA1849 // Call async methods when in an async method
try
{
targetWasAlreadyStarted = runningTargets.TryGetValue(target, out runningTarget);
if (!targetWasAlreadyStarted)
{
runningTarget = target.RunAsync(dryRun, parallel, output, messageOnly, dependencyPath);
runningTargets.Add(target, runningTarget);
}
}
finally
{
_ = sync.Release();
}
if (!targetWasAlreadyStarted || runningTarget.IsAwaitable())
{
await output.Awaiting(target, dependencyPath).Tax();
await runningTarget.Tax();
}
}
}
19
View Source File : Saml2ConfigurationManager.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public async Task<WsFederationConfiguration> GetConfigurationAsync(CancellationToken cancel)
{
if (_configuration != null && !_refreshRequested) return _configuration;
await _refreshLock.WaitAsync(cancel);
try
{
_configuration = await GetConfigurationAsync(_metadataAddress, _doreplacedentRetriever, CancellationToken.None);
_refreshRequested = false;
return _configuration;
}
finally
{
_refreshLock.Release();
}
}
19
View Source File : LogRecorder.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
private static void WriteRecordLoop()
{
bool success = true;
try
{
if (Interlocked.Increment(ref BackIsRuning) > 1)
{
return;
}
SystemTrace(LogLevel.System, "日志开始");
int cnt = 0;
while (State != LogRecorderStatus.Shutdown)
{
//Thread.Sleep(10);//让子弹飞一会
if (State < LogRecorderStatus.Initialized || !BaseRecorder.IsInitialized || !Recorder.IsInitialized)
{
Thread.Sleep(50);
continue;
}
var array = RecordInfos.Switch();
if (array.Count == 0)
{
Thread.Sleep(50);
continue;
}
foreach (var info in array)
{
if (info == null)
continue;
try
{
info.Index = ++_id;
if (_id == ulong.MaxValue)
_id = 1;
if (!_isTextRecorder && (info.Type >= LogType.System || info.Local))
BaseRecorder.RecordLog(info);
if (Listener != null || TraceToConsole)
DoTrace(info);
}
catch (Exception ex)
{
SystemTrace(LogLevel.Error, "日志写入发生错误", ex);
}
}
try
{
Recorder.RecordLog(array.ToList());
}
catch (Exception ex)
{
SystemTrace(LogLevel.Error, "日志写入发生错误", ex);
}
if (++cnt < 1024)
continue;
GC.Collect();
cnt = 0;
}
_syncSlim.Release();
}
catch (Exception e)
{
success = false;
Console.WriteLine(e);
}
finally
{
Interlocked.Decrement(ref BackIsRuning);
SystemTrace(LogLevel.System, "日志结束");
}
if (!success)
NewRecorderThread();
}
19
View Source File : IZeroObject.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public static void OnGlobalEnd(IZeroObject obj)
{
lock (GlobalObjects)
{
GlobalObjects.Remove(obj);
ZeroTrace.SystemLog(obj.Name, "GlobalEnd");
if (GlobalObjects.Count == 0)
GlobalSemapreplaced.Release();
}
}
19
View Source File : IZeroObject.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public static void OnObjectActive(IZeroObject obj)
{
lock (ActiveObjects)
{
ActiveObjects.Add(obj);
ZeroTrace.SystemLog(obj.Name, "Run");
if (ActiveObjects.Count + FailedObjects.Count == ZeroObjects.Count)
ActiveSemapreplaced.Release(); //发出完成信号
}
}
19
View Source File : IZeroObject.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public static void OnObjectClose(IZeroObject obj)
{
lock (ActiveObjects)
{
ActiveObjects.Remove(obj);
ZeroTrace.SystemLog(obj.Name, "Closed");
if (ActiveObjects.Count == 0)
ActiveSemapreplaced.Release(); //发出完成信号
}
}
19
View Source File : PollProxy.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
private void Run()
{
var configs = ZeroApplication.Config.GetConfigs(p => p.StationType != ZeroStationType.Dispatcher);
ZSocket[] sockets = new ZSocket[configs.Length * 2];
int idx = 0;
foreach (var config in configs)
{
sockets[idx++] = ZSocket.CreateServiceSocket($"inproc://{config.StationName}_Proxy", ZSocketType.ROUTER);
sockets[idx++] = ZSocket.CreateClientSocket(config.RequestAddress, ZSocketType.DEALER);
}
WaitCount = 0;
ZeroTrace.SystemLog("ConnectionProxy", "Listen");
using (var pool = ZmqPool.CreateZmqPool())
{
pool.Prepare(sockets, ZPollEvent.In);
_waitToken.Release();
//SystemManager.Instance.HeartReady(StationName, RealName);
while (!RunTaskCancel.Token.IsCancellationRequested)
{
if (!pool.Poll())
continue;
Parallel.For(0, configs.Length, index =>
{
CheckCall(pool, index * 2);
CheckResult(pool, index * 2 + 1);
});
}
}
_waitToken.Release();
}
19
View Source File : StationProxy.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
private void Run()
{
_inprocPollSocket =
ZSocket.CreateServiceSocket($"inproc://{Config.StationName}_Proxy", ZSocketType.ROUTER);
_inprocPollSocket.Backlog = 4096;
_callPollSocket = ZSocket.CreateClientSocket(Config.RequestAddress, ZSocketType.DEALER);
WaitCount = 0;
ZeroTrace.SystemLog($"{Config.StationName}(proxy)", "Listen");
_waitToken.Release();
using (var pool = ZmqPool.CreateZmqPool())
{
pool.Prepare(new[] {_inprocPollSocket, _callPollSocket}, ZPollEvent.In);
//SystemManager.Instance.HeartReady(StationName, RealName);
while (!RunTaskCancel.Token.IsCancellationRequested)
{
if (!pool.Poll())
continue;
CheckCall(pool);
CheckResult(pool);
}
}
_waitToken.Release();
}
19
View Source File : ApiStation.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
private void RunThread()
{
var realName = ZeroIdenreplacedyHelper.CreateRealName(IsService, Name == Config.StationName ? null : Name);
var idenreplacedy = realName.ToAsciiBytes();
ZeroTrace.SystemLog(StationName, "run", Config.WorkerCallAddress, Name, realName);
var socket = ZSocket.CreateClientSocket(Config.WorkerResultAddress, ZSocketType.DEALER);
using (var pool = ZmqPool.CreateZmqPool())
{
pool.Prepare(new[] {ZSocket.CreateClientSocket(Config.WorkerCallAddress, ZSocketType.PULL, idenreplacedy)},
ZPollEvent.In);
State = StationState.Run;
while (CanLoop)
{
if (!pool.Poll() || !pool.CheckIn(0, out var message))
{
continue;
}
Interlocked.Increment(ref RecvCount);
using (message)
{
if (!Unpack(message, out var item))
{
SendLayoutErrorResult(ref socket, item.Caller);
continue;
}
ApiCall(ref socket, item);
}
}
}
ZeroTrace.SystemLog(StationName, "end", Config.WorkerCallAddress, Name, realName);
socket.Dispose();
_processSemapreplaced?.Release();
}
19
View Source File : ApiStation.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
private void RunSignle()
{
var socket = ZSocket.CreateClientSocket(Config.WorkerResultAddress, ZSocketType.DEALER);
{
using (var pool = ZmqPool.CreateZmqPool())
{
pool.Prepare(new[] { ZSocket.CreateClientSocket(Config.WorkerCallAddress, ZSocketType.PULL, Idenreplacedy) }, ZPollEvent.In);
State = StationState.Run;
while (CanLoop)
{
if (!pool.Poll() || !pool.CheckIn(0, out var message))
{
continue;
}
Interlocked.Increment(ref RecvCount);
using (message)
{
if (!Unpack(message, out var item))
{
SendLayoutErrorResult(ref socket, item.Caller);
continue;
}
ApiCall(ref socket, item);
}
}
}
}
socket.Dispose();
_processSemapreplaced?.Release();
}
19
View Source File : RemoteRecorder.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
private void OnStop()
{
State = StationState.Closed;
ZeroApplication.OnObjectClose(this);
_waitToken.Release();
}
19
View Source File : SystemMonitor.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
internal static void Monitor()
{
using (OnceScope.CreateScope(ZeroApplication.Config))
{
}
using (var poll = ZmqPool.CreateZmqPool())
{
poll.Prepare(new[] { ZSocket.CreateSubscriberSocket(ZeroApplication.Config.ZeroMonitorAddress) }, ZPollEvent.In);
ZeroTrace.SystemLog("Zero center in monitor...");
TaskEndSem.Release();
while (ZeroApplication.IsAlive)
{
if (!poll.Poll() || !poll.CheckIn(0, out var message))
{
continue;
}
if (!message.Unpack(out var item))
continue;
OnMessagePush(item.ZeroEvent, item.Subreplacedle, item.Content);
}
}
TaskEndSem.Release();
}
19
View Source File : IZeroObject.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public static void OnObjectFailed(IZeroObject obj)
{
lock (ActiveObjects)
{
FailedObjects.Add(obj);
ZeroTrace.WriteError(obj.Name, "Failed");
if (ActiveObjects.Count + FailedObjects.Count == ZeroObjects.Count)
ActiveSemapreplaced.Release(); //发出完成信号
}
}
19
View Source File : ZeroApplication.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public static void Shutdown()
{
ZeroTrace.SystemLog("Begin shutdown...");
switch (ApplicationState)
{
case StationState.Destroy:
return;
case StationState.BeginRun:
case StationState.Run:
OnZeroEnd();
break;
case StationState.Failed:
SystemManager.Instance.HeartLeft();
break;
}
ApplicationState = StationState.Destroy;
if (GlobalObjects.Count > 0)
GlobalSemapreplaced.Wait();
OnZeroDestory();
SystemManager.Instance.Destroy();
LogRecorder.Shutdown();
SystemMonitor.WaitMe();
GC.Collect();
ZContext.Destroy();
ZeroTrace.SystemLog("Application shutdown ,see you late.");
ApplicationState = StationState.Disposed;
WaitToken.Release();
}
19
View Source File : ZeroStation.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
private void OnRun()
{
ZeroApplication.OnObjectActive(this);
_waitToken.Release();
}
19
View Source File : ZeroStation.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
private void Run()
{
bool success;
using (OnceScope.CreateScope(this, OnRun, OnStop))
{
try
{
success = RunInner(RunTaskCancel.Token);
}
catch (Exception e)
{
ZeroTrace.WriteException(StationName, e, "Run");
success = false;
}
}
if (ZeroApplication.CanDo && !success)
{
//自动重启
ZeroTrace.SystemLog(StationName, "ReStart");
Task.Factory.StartNew(Start);
}
else
{
_waitToken.Release();
}
GC.Collect();
}
19
View Source File : WebSocketClient.cs
License : MIT License
Project Creator : Aiko-IT-Systems
License : MIT License
Project Creator : Aiko-IT-Systems
public async Task ConnectAsync(Uri uri)
{
// Disconnect first
try { await this.DisconnectAsync().ConfigureAwait(false); } catch { }
// Disallow sending messages
await this._senderLock.WaitAsync().ConfigureAwait(false);
try
{
// This can be null at this point
this._receiverTokenSource?.Dispose();
this._socketTokenSource?.Dispose();
this._ws?.Dispose();
this._ws = new ClientWebSocket();
this._ws.Options.Proxy = this.Proxy;
this._ws.Options.KeepAliveInterval = TimeSpan.Zero;
if (this._defaultHeaders != null)
foreach (var (k, v) in this._defaultHeaders)
this._ws.Options.SetRequestHeader(k, v);
this._receiverTokenSource = new CancellationTokenSource();
this._receiverToken = this._receiverTokenSource.Token;
this._socketTokenSource = new CancellationTokenSource();
this._socketToken = this._socketTokenSource.Token;
this._isClientClose = false;
this._isDisposed = false;
await this._ws.ConnectAsync(uri, this._socketToken).ConfigureAwait(false);
this._receiverTask = Task.Run(this.ReceiverLoopAsync, this._receiverToken);
}
finally
{
this._senderLock.Release();
}
}
19
View Source File : WebSocketClient.cs
License : MIT License
Project Creator : Aiko-IT-Systems
License : MIT License
Project Creator : Aiko-IT-Systems
public async Task DisconnectAsync(int code = 1000, string message = "")
{
// Ensure that messages cannot be sent
await this._senderLock.WaitAsync().ConfigureAwait(false);
try
{
this._isClientClose = true;
if (this._ws != null && (this._ws.State == WebSocketState.Open || this._ws.State == WebSocketState.CloseReceived))
await this._ws.CloseOutputAsync((WebSocketCloseStatus)code, message, CancellationToken.None).ConfigureAwait(false);
if (this._receiverTask != null)
await this._receiverTask.ConfigureAwait(false); // Ensure that receiving completed
if (this._isConnected)
this._isConnected = false;
if (!this._isDisposed)
{
// Cancel all running tasks
if (this._socketToken.CanBeCanceled)
this._socketTokenSource?.Cancel();
this._socketTokenSource?.Dispose();
if (this._receiverToken.CanBeCanceled)
this._receiverTokenSource?.Cancel();
this._receiverTokenSource?.Dispose();
this._isDisposed = true;
}
}
catch { }
finally
{
this._senderLock.Release();
}
}
19
View Source File : VoiceTransmitSink.cs
License : MIT License
Project Creator : Aiko-IT-Systems
License : MIT License
Project Creator : Aiko-IT-Systems
public async Task WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
{
await this.WriteSemapreplaced.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
var remaining = buffer.Length;
var buffSpan = buffer;
var pcmSpan = this.PcmMemory;
while (remaining > 0)
{
var len = Math.Min(pcmSpan.Length - this.PcmBufferLength, remaining);
var tgt = pcmSpan.Slice(this.PcmBufferLength);
var src = buffSpan.Slice(0, len);
src.CopyTo(tgt);
this.PcmBufferLength += len;
remaining -= len;
buffSpan = buffSpan.Slice(len);
if (this.PcmBufferLength == this.PcmBuffer.Length)
{
this.ApplyFiltersSync(pcmSpan);
this.PcmBufferLength = 0;
var packet = ArrayPool<byte>.Shared.Rent(this.PcmMemory.Length);
var packetMemory = packet.AsMemory().Slice(0, this.PcmMemory.Length);
this.PcmMemory.CopyTo(packetMemory);
await this.Connection.EnqueuePacketAsync(new RawVoicePacket(packetMemory, this.PcmBufferDuration, false, packet), cancellationToken).ConfigureAwait(false);
}
}
}
finally
{
this.WriteSemapreplaced.Release();
}
}
19
View Source File : WebSocketClient.cs
License : MIT License
Project Creator : Aiko-IT-Systems
License : MIT License
Project Creator : Aiko-IT-Systems
public async Task SendMessageAsync(string message)
{
if (this._ws == null)
return;
if (this._ws.State != WebSocketState.Open && this._ws.State != WebSocketState.CloseReceived)
return;
var bytes = Utilities.UTF8.GetBytes(message);
await this._senderLock.WaitAsync().ConfigureAwait(false);
try
{
var len = bytes.Length;
var segCount = len / OutgoingChunkSize;
if (len % OutgoingChunkSize != 0)
segCount++;
for (var i = 0; i < segCount; i++)
{
var segStart = OutgoingChunkSize * i;
var segLen = Math.Min(OutgoingChunkSize, len - segStart);
await this._ws.SendAsync(new ArraySegment<byte>(bytes, segStart, segLen), WebSocketMessageType.Text, i == segCount - 1, CancellationToken.None).ConfigureAwait(false);
}
}
finally
{
this._senderLock.Release();
}
}
19
View Source File : CooldownAttribute.cs
License : MIT License
Project Creator : Aiko-IT-Systems
License : MIT License
Project Creator : Aiko-IT-Systems
internal async Task<bool> DecrementUseAsync()
{
await this.UsageSemapreplaced.WaitAsync().ConfigureAwait(false);
// if we're past reset time...
var now = DateTimeOffset.UtcNow;
if (now >= this.ResetsAt)
{
// ...do the reset and set a new reset time
Interlocked.Exchange(ref this._remaining_uses, this.MaxUses);
this.ResetsAt = now + this.Reset;
}
// check if we have any uses left, if we do...
var success = false;
if (this.RemainingUses > 0)
{
// ...decrement, and return success...
Interlocked.Decrement(ref this._remaining_uses);
success = true;
}
// ...otherwise just fail
this.UsageSemapreplaced.Release();
return success;
}
19
View Source File : Remote.cs
License : MIT License
Project Creator : AiursoftWeb
License : MIT License
Project Creator : AiursoftWeb
public async Task PushAsync()
{
await PushLock.WaitAsync();
var commitsToPush = ContextRepository.Commits.GetAllAfter(PushPointer).ToList();
if (commitsToPush.Any())
{
var uploaded = await ConnectionProvider.Upload(commitsToPush, PushPointer?.Id);
if(uploaded)
{
PushPointer = commitsToPush.Last();
}
}
PushLock.Release();
}
19
View Source File : Remote.cs
License : MIT License
Project Creator : AiursoftWeb
License : MIT License
Project Creator : AiursoftWeb
public async Task PullAsync()
{
if (ContextRepository == null)
{
throw new ArgumentNullException(nameof(ContextRepository), "Please add this remote to a repository.");
}
await PullLock.WaitAsync();
var downloadResult = await ConnectionProvider.Download(PullPointer?.Id);
if (downloadResult.Any())
{
ContextRepository.OnPulled(downloadResult, this);
}
PullLock.Release();
}
19
View Source File : Remote.cs
License : MIT License
Project Creator : AiursoftWeb
License : MIT License
Project Creator : AiursoftWeb
public async Task StopMonitoring()
{
await PushLock.WaitAsync();
await ConnectionProvider.Disconnect();
PushLock.Release();
}
19
View Source File : Seeder.cs
License : MIT License
Project Creator : AiursoftWeb
License : MIT License
Project Creator : AiursoftWeb
public async Task Seed()
{
try
{
await SemapreplacedSlim.WaitAsync();
await AllClear();
var result = await _http.Get(new AiurUrl(_configuration["ResourcesUrl"] + "structure.json"));
var sourceObject = JsonConvert.DeserializeObject<List<Collection>>(result);
// Get all collections
foreach (var collection in sourceObject)
{
// Insert collection
var newCollection = new Collection
{
Collectionreplacedle = collection.Collectionreplacedle,
DocAPIAddress = collection.DocAPIAddress
};
await _dbContext.Collections.AddAsync(newCollection);
await _dbContext.SaveChangesAsync();
// Get markdown from existing doreplacedents.
foreach (var article in collection.Articles ?? new List<Article>())
{
// markdown http url.
if (!string.IsNullOrEmpty(article.ArticleAddress))
{
var newArticle = new Article
{
Articlereplacedle = article.Articlereplacedle,
ArticleAddress = article.ArticleAddress,
ArticleContent = await _http.Get(new AiurUrl(article.ArticleAddress)),
CollectionId = newCollection.CollectionId
};
await _dbContext.Article.AddAsync(newArticle);
await _dbContext.SaveChangesAsync();
}
// GitHub repo.
else
{
var newArticle = new Article
{
Articlereplacedle = article.Articlereplacedle,
ArticleContent = await _http.Get(new AiurUrl($"{_configuration["ResourcesUrl"]}{collection.Collectionreplacedle}/{article.Articlereplacedle}.md")),
CollectionId = newCollection.CollectionId
};
await _dbContext.Article.AddAsync(newArticle);
await _dbContext.SaveChangesAsync();
}
}
// Parse the appended doc.
if (!string.IsNullOrWhiteSpace(collection.DocAPIAddress))
{
var doamin = _configuration["RootDomain"];
var docBuilt = collection.DocAPIAddress
.Replace("{{rootDomain}}", doamin);
// Generate markdown from doc generator
var docString = await _http.Get(new AiurUrl(docBuilt));
var docModel = JsonConvert.DeserializeObject<List<API>>(docString);
var docGrouped = docModel.GroupBy(t => t.ControllerName);
var apiRoot = docBuilt.ToLower().Replace("/doc", "");
foreach (var docController in docGrouped)
{
var markdown = _markDownGenerator.GenerateMarkDownForAPI(docController, apiRoot);
var newArticle = new Article
{
Articlereplacedle = docController.Key.TrimController(),
ArticleContent = markdown,
CollectionId = newCollection.CollectionId,
BuiltByJson = true
};
await _dbContext.Article.AddAsync(newArticle);
await _dbContext.SaveChangesAsync();
}
}
}
}
finally
{
SemapreplacedSlim.Release();
}
}
19
View Source File : Remote.cs
License : MIT License
Project Creator : AiursoftWeb
License : MIT License
Project Creator : AiursoftWeb
public async Task<Remote<T>> AttachAsync(IRepository<T> target, bool monitorInCurrentThread = false)
{
if (ContextRepository != null)
{
throw new InvalidOperationException("You can't attach a remote to more than one repository. Consider creating a new remote!");
}
ContextRepository = target;
if (AutoPush)
{
AutoPushsubscription = ContextRepository.AppendCommitsHappened.Subscribe(_ => PushAsync());
}
if (AutoPull)
{
await ConnectionProvider.PullAndMonitor(onData: async data =>
{
await PullLock.WaitAsync();
ContextRepository.OnPulled(data.ToList(), this);
PullLock.Release();
}, () => PullPointer?.Id, onConnected: () => AutoPush ? PushAsync() : Task.CompletedTask, monitorInCurrentThread);
}
return this;
}
19
View Source File : SiteRepo.cs
License : MIT License
Project Creator : AiursoftWeb
License : MIT License
Project Creator : AiursoftWeb
public async Task<Site> CreateSite(string newSiteName, bool openToUpload, bool openToDownload, string appid)
{
await _createSiteLock.WaitAsync();
try
{
await _dbContext.Sites.EnsureUniqueString(t => t.SiteName, newSiteName);
var newRootFolder = new Folder
{
FolderName = "blob"
};
await _dbContext.Folders.AddAsync(newRootFolder);
await _dbContext.SaveChangesAsync();
var site = new Site
{
AppId = appid,
SiteName = newSiteName.ToLower(),
RootFolderId = newRootFolder.Id,
OpenToUpload = openToUpload,
OpenToDownload = openToDownload
};
await _dbContext.Sites.AddAsync(site);
await _dbContext.SaveChangesAsync();
return site;
}
finally
{
_createSiteLock.Release();
}
}
19
View Source File : RecordRepo.cs
License : MIT License
Project Creator : AiursoftWeb
License : MIT License
Project Creator : AiursoftWeb
public async Task<WarpRecord> CreateRecord(string newRecordName, RecordType type, string appid, string targetUrl, bool enabled, string tags)
{
await _createRecordLock.WaitAsync();
try
{
await _table.EnsureUniqueString(t => t.RecordUniqueName, newRecordName);
var newRecord = new WarpRecord
{
RecordUniqueName = newRecordName.ToLower(),
Type = type,
AppId = appid,
TargetUrl = targetUrl,
Enabled = enabled,
Tags = tags
};
await _table.AddAsync(newRecord);
await _dbContext.SaveChangesAsync();
return newRecord;
}
finally
{
_createRecordLock.Release();
}
}
19
View Source File : FriendshipController.cs
License : MIT License
Project Creator : AiursoftWeb
License : MIT License
Project Creator : AiursoftWeb
private async Task<PrivateConversation> AcceptRequest(Request request, bool accept)
{
PrivateConversation newConversation = null;
request.Completed = true;
await semapreplacedSlim.WaitAsync();
try
{
if (accept)
{
if (await _dbContext.AreFriends(request.CreatorId, request.TargetId))
{
await _dbContext.SaveChangesAsync();
throw new AiurAPIModelException(ErrorType.HreplaceduccessAlready, "You two are already friends.");
}
newConversation = _dbContext.AddFriend(request.CreatorId, request.TargetId);
}
await _dbContext.SaveChangesAsync();
}
finally
{
semapreplacedSlim.Release();
}
await Task.WhenAll(
_pusher.FriendsChangedEvent(
request.Creator,
request,
accept,
newConversation?.Build(request.CreatorId, _onlineJudger) as PrivateConversation),
_pusher.FriendsChangedEvent(
request.Target,
request,
accept,
newConversation?.Build(request.TargetId, _onlineJudger) as PrivateConversation));
return newConversation;
}
19
View Source File : FriendshipController.cs
License : MIT License
Project Creator : AiursoftWeb
License : MIT License
Project Creator : AiursoftWeb
[HttpPost]
[APIProduces(typeof(AiurValue<int>))]
public async Task<IActionResult> CreateRequest([Required] string id)
{
var user = await GetKahlaUser();
await _dbContext.Entry(user)
.Collection(t => t.HisDevices)
.LoadAsync();
var target = await _dbContext.Users.Include(t => t.HisDevices).SingleOrDefaultAsync(t => t.Id == id);
if (target == null)
{
return this.Protocol(ErrorType.NotFound, "We can not find your target user!");
}
if (target.Id == user.Id)
{
return this.Protocol(ErrorType.Conflict, "You can't request yourself!");
}
var areFriends = await _dbContext.AreFriends(user.Id, target.Id);
if (areFriends)
{
return this.Protocol(ErrorType.Conflict, "You two are already friends!");
}
Request request;
await semapreplacedSlim.WaitAsync();
try
{
var pending = await _dbContext.Requests
.Where(t =>
t.CreatorId == user.Id && t.TargetId == target.Id ||
t.CreatorId == target.Id && t.TargetId == user.Id)
.AnyAsync(t => !t.Completed);
if (pending)
{
return this.Protocol(ErrorType.Conflict, "There are some pending request hasn't been completed!");
}
request = new Request
{
CreatorId = user.Id,
Creator = user,
TargetId = id,
};
await _dbContext.Requests.AddAsync(request);
await _dbContext.SaveChangesAsync();
}
finally
{
semapreplacedSlim.Release();
}
await Task.WhenAll(
_pusher.NewFriendRequestEvent(target, request),
_pusher.NewFriendRequestEvent(user, request)
);
if (_configuration["AutoAcceptRequests"] == true.ToString().ToLower())
{
await AcceptRequest(request, true);
}
return this.Protocol(new AiurValue<int>(request.Id)
{
Code = ErrorType.Success,
Message = "Successfully created your request!"
});
}
19
View Source File : Localization.cs
License : MIT License
Project Creator : AkiniKites
License : MIT License
Project Creator : AkiniKites
public async Task<string> GetString(string file, BaseGGUUID id)
{
if (!_cache.TryGetValue(file, out var texts))
{
await _lock.WaitAsync();
try
{
if (!_cache.TryGetValue(file, out texts))
{
texts = await LoadFile(file);
_cache[file] = texts;
}
}
finally
{
_lock.Release();
}
}
if (texts.TryGetValue(id, out var val))
return val;
return null;
}
19
View Source File : SettingsManager.cs
License : MIT License
Project Creator : AkiniKites
License : MIT License
Project Creator : AkiniKites
private static void Save(UserSettings settings)
{
try
{
_lock.Wait();
Paths.CheckDirectory(ApplicationSettingsPath);
using var backup = new FileBackup(SettingsPath);
var json = JsonConvert.SerializeObject(settings, Formatting.Indented);
File.WriteAllText(SettingsPath, json);
backup.Delete();
}
finally
{
_lock.Release();
}
}
19
View Source File : AsyncReaderWriterLock.cs
License : MIT License
Project Creator : AkiniKites
License : MIT License
Project Creator : AkiniKites
public void ExitWriteLock()
{
_readSemapreplaced.Release();
_writeSemapreplaced.Release();
}
19
View Source File : AsyncReaderWriterLock.cs
License : MIT License
Project Creator : AkiniKites
License : MIT License
Project Creator : AkiniKites
public async Task EnterReadLock(CancellationToken token = default)
{
await _writeSemapreplaced.WaitAsync(token).ConfigureAwait(false);
if (Interlocked.Increment(ref _readerCount) == 1)
{
try
{
await SafeAcquireReadSemapreplaced(token).ConfigureAwait(false);
}
catch
{
Interlocked.Decrement(ref _readerCount);
throw;
}
}
_writeSemapreplaced.Release();
}
19
View Source File : AsyncReaderWriterLock.cs
License : MIT License
Project Creator : AkiniKites
License : MIT License
Project Creator : AkiniKites
public void ExitReadLock()
{
if (Interlocked.Decrement(ref _readerCount) == 0)
_readSemapreplaced.Release();
}
19
View Source File : AsyncReaderWriterLock.cs
License : MIT License
Project Creator : AkiniKites
License : MIT License
Project Creator : AkiniKites
private async Task SafeAcquireReadSemapreplaced(CancellationToken token)
{
try
{
await _readSemapreplaced.WaitAsync(token).ConfigureAwait(false);
}
catch
{
_writeSemapreplaced.Release();
throw;
}
}
19
View Source File : LimitedConcurrentStack.cs
License : MIT License
Project Creator : AkiniKites
License : MIT License
Project Creator : AkiniKites
public void CompleteAdding()
{
lock (_lock)
{
if (!_complete)
{
_waitingCount.Release();
_complete = true;
}
}
}
19
View Source File : LimitedConcurrentStack.cs
License : MIT License
Project Creator : AkiniKites
License : MIT License
Project Creator : AkiniKites
public void Push(T item)
{
lock (_lock)
{
if (_complete)
throw new InvalidOperationException("Collection is complete adding.");
var oldItem = _items[_head];
_items[_head] = item;
_head = (_head + 1) % _items.Length;
if (_waitingCount.CurrentCount < 10)
{
_waitingCount.Release();
_count++;
}
else
{
ItemDropped?.Invoke(oldItem);
}
}
}
See More Examples