Here are the examples of the csharp api System.Threading.Interlocked.Increment(ref long) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1356 Examples
19
View Source File : ObjectPool.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public Object<T> Get(TimeSpan? timeout = null)
{
var obj = getFree(true);
if (obj == null)
{
var queueItem = new GetSyncQueueInfo();
_getSyncQueue.Enqueue(queueItem);
_getQueue.Enqueue(false);
if (timeout == null) timeout = Policy.SyncGetTimeout;
try
{
if (queueItem.Wait.Wait(timeout.Value))
obj = queueItem.ReturnValue;
}
catch { }
if (obj == null) obj = queueItem.ReturnValue;
if (obj == null) lock (queueItem.Lock) queueItem.IsTimeout = (obj = queueItem.ReturnValue) == null;
if (obj == null) obj = queueItem.ReturnValue;
if (obj == null)
{
Policy.OnGetTimeout();
if (Policy.IsThrowGetTimeoutException)
throw new TimeoutException($"SafeObjectPool.Get 获取超时({timeout.Value.TotalSeconds}秒)。");
return null;
}
}
try
{
Policy.OnGet(obj);
}
catch
{
Return(obj);
throw;
}
obj.LastGetThreadId = Thread.CurrentThread.ManagedThreadId;
obj.LastGetTime = DateTime.Now;
Interlocked.Increment(ref obj._getTimes);
return obj;
}
19
View Source File : ObjectPool.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
async public Task<Object<T>> GetAsync()
{
var obj = getFree(true);
if (obj == null)
{
if (Policy.AsyncGetCapacity > 0 && _getAsyncQueue.Count >= Policy.AsyncGetCapacity - 1)
throw new OutOfMemoryException($"SafeObjectPool.GetAsync 无可用资源且队列过长,Policy.AsyncGetCapacity = {Policy.AsyncGetCapacity}。");
var tcs = new TaskCompletionSource<Object<T>>();
_getAsyncQueue.Enqueue(tcs);
_getQueue.Enqueue(true);
obj = await tcs.Task;
//if (timeout == null) timeout = Policy.SyncGetTimeout;
//if (tcs.Task.Wait(timeout.Value))
// obj = tcs.Task.Result;
//if (obj == null) {
// tcs.TrySetCanceled();
// Policy.GetTimeout();
// if (Policy.IsThrowGetTimeoutException)
// throw new Exception($"SafeObjectPool.GetAsync 获取超时({timeout.Value.TotalSeconds}秒)。");
// return null;
//}
}
try
{
await Policy.OnGetAsync(obj);
}
catch
{
Return(obj);
throw;
}
obj.LastGetThreadId = Thread.CurrentThread.ManagedThreadId;
obj.LastGetTime = DateTime.Now;
Interlocked.Increment(ref obj._getTimes);
return obj;
}
19
View Source File : ObjectPool.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public Object<T> Get(TimeSpan? timeout = null)
{
var obj = GetFree(true);
if (obj == null)
{
var queueItem = new GetSyncQueueInfo();
_getSyncQueue.Enqueue(queueItem);
_getQueue.Enqueue(false);
if (timeout == null) timeout = Policy.SyncGetTimeout;
try
{
if (queueItem.Wait.Wait(timeout.Value))
obj = queueItem.ReturnValue;
}
catch { }
if (obj == null) obj = queueItem.ReturnValue;
if (obj == null) lock (queueItem.Lock) queueItem.IsTimeout = (obj = queueItem.ReturnValue) == null;
if (obj == null) obj = queueItem.ReturnValue;
if (obj == null)
{
Policy.OnGetTimeout();
if (Policy.IsThrowGetTimeoutException)
throw new TimeoutException($"ObjectPool.Get() timeout {timeout.Value.TotalSeconds} seconds");
return null;
}
}
try
{
Policy.OnGet(obj);
}
catch
{
Return(obj);
throw;
}
obj.LastGetThreadId = Thread.CurrentThread.ManagedThreadId;
obj.LastGetTime = DateTime.Now;
Interlocked.Increment(ref obj._getTimes);
return obj;
}
19
View Source File : IdleBus`1.ItemInfo.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
internal TValue GetOrCreate()
{
if (isdisposed == true) return null;
if (value == null)
{
var iscreate = false;
var now = DateTime.Now;
try
{
lock (valueLock)
{
if (isdisposed == true) return null;
if (value == null)
{
value = create();
createTime = DateTime.Now;
Interlocked.Increment(ref ib._usageQuanreplacedy);
iscreate = true;
}
else
{
return value;
}
}
if (iscreate)
{
if (value != null)
{
if (firstValue == null) firstValue = value; //记录首次值
else if (firstValue == value) IsRegisterError = true; //第二次与首次相等,注册姿势错误
}
ib.OnNotice(new NoticeEventArgs(NoticeType.AutoCreate, key, null, $"{key} 实例+++创建成功,耗时 {DateTime.Now.Subtract(now).TotalMilliseconds}ms,{ib._usageQuanreplacedy}/{ib.Quanreplacedy}"));
}
}
catch (Exception ex)
{
ib.OnNotice(new NoticeEventArgs(NoticeType.AutoCreate, key, ex, $"{key} 实例+++创建失败:{ex.Message}"));
throw;
}
}
lastActiveTime = DateTime.Now;
Interlocked.Increment(ref activeCounter);
return value;
}
19
View Source File : IdleBus`1.ItemInfo.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
internal TValue GetOrCreate()
{
if (isdisposed == true) return null;
if (value == null)
{
var iscreate = false;
var now = DateTime.Now;
try
{
lock (valueLock)
{
if (isdisposed == true) return null;
if (value == null)
{
value = create();
createTime = DateTime.Now;
Interlocked.Increment(ref ib._usageQuanreplacedy);
iscreate = true;
}
else
{
return value;
}
}
if (iscreate)
{
if (value != null)
{
if (firstValue == null) firstValue = value; //记录首次值
else if (firstValue == value) IsRegisterError = true; //第二次与首次相等,注册姿势错误
}
ib.OnNotice(new NoticeEventArgs(NoticeType.AutoCreate, key, null, $"{key} 实例+++创建成功,耗时 {DateTime.Now.Subtract(now).TotalMilliseconds}ms,{ib._usageQuanreplacedy}/{ib.Quanreplacedy}"));
}
}
catch (Exception ex)
{
ib.OnNotice(new NoticeEventArgs(NoticeType.AutoCreate, key, ex, $"{key} 实例+++创建失败:{ex.Message}"));
throw;
}
}
lastActiveTime = DateTime.Now;
Interlocked.Increment(ref activeCounter);
return value;
}
19
View Source File : IdleBus`1.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
void InternalRemoveDelayHandler()
{
//处理延时删除
var removeKeys = _removePending.Keys;
foreach (var removeKey in removeKeys)
{
if (_removePending.TryGetValue(removeKey, out var removeItem) == false) continue;
if (DateTime.Now.Subtract(removeItem.lastActiveTime) <= removeItem.idle) continue;
try
{
removeItem.Release(() => true);
}
catch (Exception ex)
{
var tmp1 = Interlocked.Increment(ref removeItem.releaseErrorCounter);
this.OnNotice(new NoticeEventArgs(NoticeType.Remove, removeItem.key, ex, $"{removeKey} ---延时释放执行出错({tmp1}次):{ex.Message}"));
if (tmp1 < 3)
continue;
}
removeItem.Dispose();
_removePending.TryRemove(removeKey, out var oldItem);
}
}
19
View Source File : ObjectPool.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
async public Task<Object<T>> GetAsync()
{
var obj = GetFree(true);
if (obj == null)
{
if (Policy.AsyncGetCapacity > 0 && _getAsyncQueue.Count >= Policy.AsyncGetCapacity - 1)
throw new OutOfMemoryException($"ObjectPool.GetAsync() The queue is too long. Policy.AsyncGetCapacity = {Policy.AsyncGetCapacity}");
var tcs = new TaskCompletionSource<Object<T>>();
_getAsyncQueue.Enqueue(tcs);
_getQueue.Enqueue(true);
obj = await tcs.Task;
//if (timeout == null) timeout = Policy.SyncGetTimeout;
//if (tcs.Task.Wait(timeout.Value))
// obj = tcs.Task.Result;
//if (obj == null) {
// tcs.TrySetCanceled();
// Policy.GetTimeout();
// if (Policy.IsThrowGetTimeoutException)
// throw new Exception($"ObjectPool.GetAsync() timeout {timeout.Value.TotalSeconds} seconds");
// return null;
//}
}
try
{
await Policy.OnGetAsync(obj);
}
catch
{
Return(obj);
throw;
}
obj.LastGetThreadId = Thread.CurrentThread.ManagedThreadId;
obj.LastGetTime = DateTime.Now;
Interlocked.Increment(ref obj._getTimes);
return obj;
}
19
View Source File : ConnectClient.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
private byte[] ReceiveBytes(int countByte)
{
//if (!Loger.IsServer) Loger.Log("Client ReceiveBytes " + countByte.ToString() + ", " + Client.ReceiveBufferSize);
//результат
byte[] msg = new byte[countByte];
//сколько уже считано
int offset = 0;
//буфер результата
byte[] receiveBuffer = new byte[Client.ReceiveBufferSize];
//кол-во считано байт последний раз
int numberOfBytesRead = 0;
//длина передаваемого сообщения (принимается в первых 4 байтах (константа Int32Length))
int lenghtAllMessageByte = countByte;
var timeOut = DateTime.UtcNow.AddMilliseconds(SilenceTime);
while (lenghtAllMessageByte > 0)
{
int maxCountRead = receiveBuffer.Length;
if (maxCountRead > lenghtAllMessageByte) maxCountRead = lenghtAllMessageByte;
//numberOfBytesRead = ClientStream.Read(receiveBuffer, 0, maxCountRead);
var receiveId = Interlocked.Increment(ref ReceiveId);
ClientStream.BeginRead(receiveBuffer, 0, maxCountRead, ReceiveBytescallback, receiveId);
while (!ReceiveReady.ContainsKey(receiveId)
&& timeOut > DateTime.UtcNow)
Thread.Sleep(1);
lock (ReceiveReady)
{
if (ReceiveReady.ContainsKey(receiveId))
{
var objRes = ReceiveReady[receiveId];
if (objRes is Exception) throw (Exception)objRes;
numberOfBytesRead = (int)ReceiveReady[receiveId];
ReceiveReady.Remove(receiveId);
}
else
throw new ConnectSilenceTimeOutException();
}
if (!Client.Client.Connected)
{
throw new ConnectNotConnectedException();
}
if (numberOfBytesRead == 0)
{
if (timeOut < DateTime.UtcNow)
throw new ConnectSilenceTimeOutException();
Thread.Sleep(1);
}
else
{
timeOut = DateTime.UtcNow.AddMilliseconds(SilenceTime);
Buffer.BlockCopy(receiveBuffer, 0, msg, offset, numberOfBytesRead);
offset += numberOfBytesRead;
lenghtAllMessageByte -= numberOfBytesRead;
}
};
return msg;
}
19
View Source File : DatabasePerfTest.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
private void Run(Session session, int biotasPerTest)
{
CommandHandlerHelper.WriteOutputInfo(session, $"Starting Shard Database Performance Tests.\nBiotas per test: {biotasPerTest}\nThis may take several minutes to complete...\nCurrent database queue count: {DatabaseManager.Shard.QueueCount}");
// Get the current queue wait time
bool responseReceived = false;
DatabaseManager.Shard.GetCurrentQueueWaitTime(result =>
{
CommandHandlerHelper.WriteOutputInfo(session, $"Current database queue wait time: {result.TotalMilliseconds:N0} ms");
responseReceived = true;
});
while (!responseReceived)
Thread.Sleep(1);
// Generate Individual WorldObjects
var biotas = new Collection<(Biota biota, ReaderWriterLockSlim rwLock)>();
for (int i = 0; i < biotasPerTest; i++)
{
var worldObject = WorldObjectFactory.CreateNewWorldObject(testWeenies[i % testWeenies.Count]);
// TODO fix this
//biotas.Add((worldObject.Biota, worldObject.BiotaDatabaseLock));
}
// Add biotasPerTest biotas individually
long trueResults = 0;
long falseResults = 0;
var startTime = DateTime.UtcNow;
var initialQueueWaitTime = TimeSpan.Zero;
var totalQueryExecutionTime = TimeSpan.Zero;
foreach (var biota in biotas)
{
/* todo
DatabaseManager.Shard.SaveBiota(biota.biota, biota.rwLock, result =>
{
if (result)
Interlocked.Increment(ref trueResults);
else
Interlocked.Increment(ref falseResults);
}, (queueWaitTime, queryExecutionTime) =>
{
if (initialQueueWaitTime == TimeSpan.Zero)
initialQueueWaitTime = queueWaitTime;
totalQueryExecutionTime += queryExecutionTime;
});*/
}
while (Interlocked.Read(ref trueResults) + Interlocked.Read(ref falseResults) < biotas.Count)
Thread.Sleep(1);
var endTime = DateTime.UtcNow;
ReportResult(session, "individual add", biotasPerTest, (endTime - startTime), initialQueueWaitTime, totalQueryExecutionTime, trueResults, falseResults);
// Update biotasPerTest biotas individually
if (session == null || SessionIsStillInWorld(session))
{
ModifyBiotas(biotas);
trueResults = 0;
falseResults = 0;
startTime = DateTime.UtcNow;
initialQueueWaitTime = TimeSpan.Zero;
totalQueryExecutionTime = TimeSpan.Zero;
foreach (var biota in biotas)
{
/* todo
DatabaseManager.Shard.SaveBiota(biota.biota, biota.rwLock, result =>
{
if (result)
Interlocked.Increment(ref trueResults);
else
Interlocked.Increment(ref falseResults);
}, (queueWaitTime, queryExecutionTime) =>
{
if (initialQueueWaitTime == TimeSpan.Zero)
initialQueueWaitTime = queueWaitTime;
totalQueryExecutionTime += queryExecutionTime;
});*/
}
while (Interlocked.Read(ref trueResults) + Interlocked.Read(ref falseResults) < biotas.Count)
Thread.Sleep(1);
endTime = DateTime.UtcNow;
ReportResult(session, "individual save", biotasPerTest, (endTime - startTime), initialQueueWaitTime, totalQueryExecutionTime, trueResults, falseResults);
}
// Delete biotasPerTest biotas individually
trueResults = 0;
falseResults = 0;
startTime = DateTime.UtcNow;
initialQueueWaitTime = TimeSpan.Zero;
totalQueryExecutionTime = TimeSpan.Zero;
foreach (var biota in biotas)
{
DatabaseManager.Shard.RemoveBiota(biota.biota.Id, result =>
{
if (result)
Interlocked.Increment(ref trueResults);
else
Interlocked.Increment(ref falseResults);
}, (queueWaitTime, queryExecutionTime) =>
{
if (initialQueueWaitTime == TimeSpan.Zero)
initialQueueWaitTime = queueWaitTime;
totalQueryExecutionTime += queryExecutionTime;
});
}
while (Interlocked.Read(ref trueResults) + Interlocked.Read(ref falseResults) < biotas.Count)
Thread.Sleep(1);
endTime = DateTime.UtcNow;
ReportResult(session, "individual remove", biotasPerTest, (endTime - startTime), initialQueueWaitTime, totalQueryExecutionTime, trueResults, falseResults);
if (session != null && !SessionIsStillInWorld(session))
return;
// Generate Bulk WorldObjects
biotas.Clear();
for (int i = 0; i < biotasPerTest; i++)
{
var worldObject = WorldObjectFactory.CreateNewWorldObject(testWeenies[i % testWeenies.Count]);
// TODO fix this
//biotas.Add((worldObject.Biota, worldObject.BiotaDatabaseLock));
}
// Add biotasPerTest biotas in bulk
trueResults = 0;
falseResults = 0;
startTime = DateTime.UtcNow;
initialQueueWaitTime = TimeSpan.Zero;
totalQueryExecutionTime = TimeSpan.Zero;
/* todo
DatabaseManager.Shard.SaveBiotasInParallel(biotas, result =>
{
if (result)
Interlocked.Increment(ref trueResults);
else
Interlocked.Increment(ref falseResults);
}, (queueWaitTime, queryExecutionTime) =>
{
if (initialQueueWaitTime == TimeSpan.Zero)
initialQueueWaitTime = queueWaitTime;
totalQueryExecutionTime += queryExecutionTime;
});*/
while (Interlocked.Read(ref trueResults) + Interlocked.Read(ref falseResults) < 1)
Thread.Sleep(1);
endTime = DateTime.UtcNow;
ReportResult(session, "bulk add", biotasPerTest, (endTime - startTime), initialQueueWaitTime, totalQueryExecutionTime, trueResults, falseResults);
// Update biotasPerTest biotas in bulk
if (session == null || SessionIsStillInWorld(session))
{
ModifyBiotas(biotas);
trueResults = 0;
falseResults = 0;
startTime = DateTime.UtcNow;
initialQueueWaitTime = TimeSpan.Zero;
totalQueryExecutionTime = TimeSpan.Zero;
/* todo
DatabaseManager.Shard.SaveBiotasInParallel(biotas, result =>
{
if (result)
Interlocked.Increment(ref trueResults);
else
Interlocked.Increment(ref falseResults);
}, (queueWaitTime, queryExecutionTime) =>
{
if (initialQueueWaitTime == TimeSpan.Zero)
initialQueueWaitTime = queueWaitTime;
totalQueryExecutionTime += queryExecutionTime;
});*/
while (Interlocked.Read(ref trueResults) + Interlocked.Read(ref falseResults) < 1)
Thread.Sleep(1);
endTime = DateTime.UtcNow;
ReportResult(session, "bulk save", biotasPerTest, (endTime - startTime), initialQueueWaitTime, totalQueryExecutionTime, trueResults, falseResults);
}
// Delete biotasPerTest biotas in bulk
trueResults = 0;
falseResults = 0;
startTime = DateTime.UtcNow;
initialQueueWaitTime = TimeSpan.Zero;
totalQueryExecutionTime = TimeSpan.Zero;
var ids = biotas.Select(r => r.biota.Id).ToList();
DatabaseManager.Shard.RemoveBiotasInParallel(ids, result =>
{
if (result)
Interlocked.Increment(ref trueResults);
else
Interlocked.Increment(ref falseResults);
}, (queueWaitTime, queryExecutionTime) =>
{
if (initialQueueWaitTime == TimeSpan.Zero)
initialQueueWaitTime = queueWaitTime;
totalQueryExecutionTime += queryExecutionTime;
});
while (Interlocked.Read(ref trueResults) + Interlocked.Read(ref falseResults) < 1)
Thread.Sleep(1);
endTime = DateTime.UtcNow;
ReportResult(session, "bulk remove", biotasPerTest, (endTime - startTime), initialQueueWaitTime, totalQueryExecutionTime, trueResults, falseResults);
if (session != null && !SessionIsStillInWorld(session))
return;
CommandHandlerHelper.WriteOutputInfo(session, "Database Performance Tests Completed");
}
19
View Source File : NetworkStatistics.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
public static long C2S_CRCErrors_Aggregate_Increment() { return Interlocked.Increment(ref Instance._C2S_CRCErrors_Aggregate); }
19
View Source File : NetworkStatistics.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
public static long C2S_RequestsForRetransmit_Aggregate_Increment() { return Interlocked.Increment(ref Instance._C2S_RequestsForRetransmit_Aggregate); }
19
View Source File : NetworkStatistics.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
public static long C2S_Packets_Aggregate_Increment() { return Interlocked.Increment(ref Instance._C2S_Packets_Aggregate); }
19
View Source File : NetworkStatistics.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
public static long S2C_RequestsForRetransmit_Aggregate_Increment() { return Interlocked.Increment(ref Instance._S2C_RequestsForRetransmit_Aggregate); }
19
View Source File : NetworkStatistics.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
public static long S2C_Packets_Aggregate_Increment() { return Interlocked.Increment(ref Instance._S2C_Packets_Aggregate); }
19
View Source File : VssFileStorage.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public void NotifyChanged()
{
using (new ReadLockScope(m_lock))
{
Interlocked.Increment(ref m_outstandingRefreshId);
}
}
19
View Source File : ProcessExtensions.cs
License : Apache License 2.0
Project Creator : adamralph
License : Apache License 2.0
Project Creator : adamralph
public static void Run(this Process process, bool noEcho, string echoPrefix, CancellationToken cancellationToken)
{
var cancelled = 0L;
if (!noEcho)
{
Console.Out.WriteLine(process.GetMessage(echoPrefix));
}
_ = process.Start();
using (cancellationToken.Register(
() =>
{
if (process.TryKill())
{
_ = Interlocked.Increment(ref cancelled);
}
},
useSynchronizationContext: false))
{
process.WaitForExit();
}
if (Interlocked.Read(ref cancelled) == 1)
{
cancellationToken.ThrowIfCancellationRequested();
}
}
19
View Source File : ParallelLoopWorker.cs
License : The Unlicense
Project Creator : aeroson
License : The Unlicense
Project Creator : aeroson
internal void Work()
{
if (threadStart != null)
{
threadStart();
}
threadStart = null;
while (true)
{
//When the owning ParallelLooper is told to start a loop, it will notify the worker via this signal.
getToWork.WaitOne();
if (manager.currentLoopBody == null)
{
//Woops, looks like it's time for me to die.
manager.OnWorkerFinish();
return;
}
while (manager.jobIndex <= manager.maxJobIndex)
{
//Claim a piece of job.
int jobIndex = Interlocked.Increment(ref manager.jobIndex);
//The job interval.
int endIndex = jobIndex * iterationsPerSteal;
int beginIndex = endIndex - iterationsPerSteal;
//Do the job piece. Make sure you don't do more than exists in the list itself.
for (int i = beginIndex; i < endIndex && i < finalIndex; i++)
{
manager.currentLoopBody(i);
}
} //this is not 'thread safe' but the result of the unsafety is a quick fail in the worst case.
manager.OnWorkerFinish();
}
}
19
View Source File : EntityBase.cs
License : The Unlicense
Project Creator : aeroson
License : The Unlicense
Project Creator : aeroson
void InitializeId()
{
InstanceId = System.Threading.Interlocked.Increment(ref idCounter);
hashCode = (int)((((ulong)InstanceId) * 4294967311UL) % 4294967296UL);
}
19
View Source File : ConnectionPool.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public RedisConnection2 GetConnection()
{
var conn = GetFreeConnection();
if (conn == null)
{
var wait = new ManualResetEventSlim(false);
lock (_lock_GetConnectionQueue)
{
GetConnectionQueue.Enqueue(wait);
}
if (wait.Wait(TimeSpan.FromSeconds(10)))
return GetConnection();
throw new Exception("CSRedis.ConnectionPool.GetConnection 连接池获取超时(10秒)");
}
if (conn.Client.IsConnected == false || DateTime.Now.Subtract(conn.LastActive).TotalSeconds > 60)
try
{
conn.Client.Ping();
}
catch
{
var ips = Dns.GetHostAddresses(_ip);
if (ips.Length == 0) throw new Exception($"无法解析“{_ip}”");
try
{
conn.Client.Dispose();
}
catch
{
}
conn.Client = new RedisClient(new IPEndPoint(ips[0], _port));
conn.Client.Connected += Connected;
}
conn.ThreadId = Thread.CurrentThread.ManagedThreadId;
conn.LastActive = DateTime.Now;
Interlocked.Increment(ref conn.UseSum);
return conn;
}
19
View Source File : ConnectionPool.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public async Task<RedisConnection2> GetConnectionAsync()
{
var conn = GetFreeConnection();
if (conn == null)
{
var tcs = new TaskCompletionSource<RedisConnection2>();
lock (_lock_GetConnectionQueue)
{
GetConnectionAsyncQueue.Enqueue(tcs);
}
conn = await tcs.Task;
}
if (conn.Client.IsConnected == false || DateTime.Now.Subtract(conn.LastActive).TotalSeconds > 60)
try
{
await conn.Client.PingAsync();
}
catch
{
var ips = Dns.GetHostAddresses(_ip);
if (ips.Length == 0) throw new Exception($"无法解析“{_ip}”");
try
{
conn.Client.Dispose();
}
catch
{
}
conn.Client = new RedisClient(new IPEndPoint(ips[0], _port));
conn.Client.Connected += Connected;
}
conn.ThreadId = Thread.CurrentThread.ManagedThreadId;
conn.LastActive = DateTime.Now;
Interlocked.Increment(ref conn.UseSum);
return conn;
}
19
View Source File : HtttpTester.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
protected override void DoAsync()
{
HttpApiCaller caller = new HttpApiCaller(Host);
caller.CreateRequest($"{Station}/{Api}","POST",Arg);
var result = caller.GetResult().Result;
if (caller.Status != WebExceptionStatus.Success)
Interlocked.Increment(ref NetError);
}
19
View Source File : Tester.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
void Async()
{
Interlocked.Increment(ref WaitCount);
GlobalContext.SetRequestContext(ZeroApplication.Config.ServiceName, Guid.NewGuid().ToString("N"));
DateTime s = DateTime.Now;
DoAsync();
Interlocked.Decrement(ref WaitCount);
var sp = (DateTime.Now - s);
Interlocked.Add(ref RunTime, sp.Ticks);
if (sp.TotalMilliseconds > 500)
Interlocked.Increment(ref TmError);
if ((Interlocked.Increment(ref ExCount) % 100) == 0)
Count();
}
19
View Source File : ZeroTester.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
protected override void DoAsync()
{
var arg = new MachineEventArg
{
EventName = "OpenDoor",
MachineId = $"Machine-{random.Next()}",
JsonStr = JsonConvert.SerializeObject(new OpenDoorArg
{
CompanyId ="��˾id",
UserType ="�û�����",
UserId = random.Next().ToString(),
DeviceId ="�豸id",
RecordDate=DateTime.Now.ToString(),
RecordUserStatus="״̬",
InOrOut= $"{((random.Next() % 2) == 1 ? "��" : "��")}",
EnterType="������ʽ",
PhotoUrl="������",
IdenreplacedyImageUrl="֤����",
PanoramaUrl="ȫ����",
Score="ʶ��ϵ��"
})
};
ApiClient client = new ApiClient
{
Station = Station,
Commmand = Api,
Argument = JsonConvert.SerializeObject(arg)
};
client.CallCommand();
if (client.State < ZeroOperatorStateType.Failed)
{
}
else if (client.State < ZeroOperatorStateType.Error)
{
Interlocked.Increment(ref BlError);
}
else if (client.State < ZeroOperatorStateType.TimeOut)
{
Interlocked.Increment(ref WkError);
}
else if (client.State > ZeroOperatorStateType.LocalNoReady)
{
Interlocked.Increment(ref ExError);
}
else
{
Interlocked.Increment(ref NetError);
}
}
19
View Source File : Program.cs
License : MIT License
Project Creator : Airkek
License : MIT License
Project Creator : Airkek
static void Worker()
{
while (true)
{
try
{
using (var req = new HttpRequest()
{
Proxy = scraper.Next(),
Cookies = new CookieStorage()
})
{
req.UserAgentRandomize();
req.Cookies.Container.Add(new Uri("https://www.youtube.com"), new Cookie("CONSENT", "YES+cb.20210629-13-p0.en+FX+407"));
var sres = req.Get($"https://www.youtube.com/watch?v={id}").ToString();
var viewersTemp = string.Join("", RegularExpressions.Viewers.Match(sres).Groups[1].Value.Where(char.IsDigit));
if (!string.IsNullOrEmpty(viewersTemp))
viewers = viewersTemp;
replacedle = RegularExpressions.replacedle.Match(sres).Groups[1].Value;
var url = RegularExpressions.ViewUrl.Match(sres).Groups[1].Value;
url = url.Replace(@"\u0026", "&").Replace("%2C", ",").Replace(@"\/", "/");
var query = System.Web.HttpUtility.ParseQueryString(url);
var cl = query.Get(query.AllKeys[0]);
var ei = query.Get("ei");
var of = query.Get("of");
var vm = query.Get("vm");
var cpn = GetCPN();
var start = DateTime.UtcNow;
var st = random.Next(1000, 10000);
var et = GetCmt(start);
var lio = GetLio(start);
var rt = random.Next(10, 200);
var lact = random.Next(1000, 8000);
var rtn = rt + 300;
var args = new Dictionary<string, string>
{
["ns"] = "yt",
["el"] = "detailpage",
["cpn"] = cpn,
["docid"] = id,
["ver"] = "2",
["cmt"] = et.ToString(),
["ei"] = ei,
["fmt"] = "243",
["fs"] = "0",
["rt"] = rt.ToString(),
["of"] = of,
["euri"] = "",
["lact"] = lact.ToString(),
["live"] = "dvr",
["cl"] = cl,
["state"] = "playing",
["vm"] = vm,
["volume"] = "100",
["cbr"] = "Firefox",
["cbrver"] = "83.0",
["c"] = "WEB",
["cplayer"] = "UNIPLAYER",
["cver"] = "2.20201210.01.00",
["cos"] = "Windows",
["cosver"] = "10.0",
["cplatform"] = "DESKTOP",
["delay"] = "5",
["hl"] = "en_US",
["rtn"] = rtn.ToString(),
["aftm"] = "140",
["rti"] = rt.ToString(),
["muted"] = "0",
["st"] = st.ToString(),
["et"] = et.ToString(),
["lio"] = lio.ToString()
};
string urlToGet = buildUrl(args);
req.AcceptEncoding ="gzip, deflate";
req.AddHeader("Host", "www.youtube.com");
req.Get(urlToGet.Replace("watchtime", "playback"));
req.AcceptEncoding ="gzip, deflate";
req.AddHeader("Host", "www.youtube.com");
req.Get(urlToGet);
Interlocked.Increment(ref botted);
}
}
catch
{
Interlocked.Increment(ref errors);
}
Thread.Sleep(1);
}
}
19
View Source File : GuidHelper.cs
License : MIT License
Project Creator : aishang2015
License : MIT License
Project Creator : aishang2015
public Guid Next()
{
var guidBytes = Guid.NewGuid().ToByteArray();
var counterBytes = BitConverter.GetBytes(Interlocked.Increment(ref _counter));
if (!BitConverter.IsLittleEndian)
{
Array.Reverse(counterBytes);
}
guidBytes[08] = counterBytes[1];
guidBytes[09] = counterBytes[0];
guidBytes[10] = counterBytes[7];
guidBytes[11] = counterBytes[6];
guidBytes[12] = counterBytes[5];
guidBytes[13] = counterBytes[4];
guidBytes[14] = counterBytes[3];
guidBytes[15] = counterBytes[2];
return new Guid(guidBytes);
}
19
View Source File : Interval.cs
License : Apache License 2.0
Project Creator : akarnokd
License : Apache License 2.0
Project Creator : akarnokd
private void Next(Task t)
{
if (t.IsCanceled || _cts.IsCancellationRequested)
{
ResumeHelper.Resume(ref _resume);
return;
}
var value = Interlocked.Increment(ref _available);
ResumeHelper.Resume(ref _resume);
if (value != _end)
{
// FIXME compensate for drifts
Task.Delay(_period, _cts.Token)
.ContinueWith(NextAction, this);
}
}
19
View Source File : MaybeConcatEager.cs
License : Apache License 2.0
Project Creator : akarnokd
License : Apache License 2.0
Project Creator : akarnokd
internal override void Drain()
{
if (Interlocked.Increment(ref wip) != 1)
{
return;
}
var missed = 1;
var observers = this.observers;
var downstream = this.downstream;
var delayErrors = this.delayErrors;
var sources = this.sources;
var n = sources.Length;
for (; ; )
{
if (Volatile.Read(ref disposed))
{
while (observers.TryDequeue(out var inner))
{
inner.Dispose();
}
}
else
{
if (!delayErrors)
{
var ex = Volatile.Read(ref errors);
if (ex != null)
{
Volatile.Write(ref disposed, true);
downstream.OnError(ex);
continue;
}
}
var idx = index;
if (active < maxConcurrency && idx < n)
{
var src = sources[idx];
index = idx + 1;
active++;
SubscribeTo(src);
continue;
}
var d = index == n;
var empty = !observers.TryPeek(out var inner);
if (d && empty)
{
Volatile.Write(ref disposed, true);
var ex = Volatile.Read(ref errors);
if (ex != null)
{
downstream.OnError(ex);
}
else
{
downstream.OnCompleted();
}
}
else
if (!empty)
{
var state = inner.GetState();
if (state == 1)
{
downstream.OnNext(inner.value);
observers.TryDequeue(out var _);
active--;
continue;
}
else
if (state == 2)
{
observers.TryDequeue(out var _);
active--;
continue;
}
}
}
missed = Interlocked.Add(ref wip, -missed);
if (missed == 0)
{
break;
}
}
}
19
View Source File : MaybeConcatEagerEnumerable.cs
License : Apache License 2.0
Project Creator : akarnokd
License : Apache License 2.0
Project Creator : akarnokd
internal override void Drain()
{
if (Interlocked.Increment(ref wip) != 1)
{
return;
}
var missed = 1;
var observers = this.observers;
var downstream = this.downstream;
var delayErrors = this.delayErrors;
var sources = this.sources;
for (; ; )
{
if (Volatile.Read(ref disposed))
{
while (observers.TryDequeue(out var inner))
{
inner.Dispose();
}
if (sources != null)
{
this.sources = null;
sources.Dispose();
}
}
else
{
if (!delayErrors)
{
var ex = Volatile.Read(ref errors);
if (ex != null)
{
Volatile.Write(ref disposed, true);
downstream.OnError(ex);
continue;
}
}
if (active < maxConcurrency && !done)
{
var src = default(IMaybeSource<T>);
try
{
if (sources.MoveNext())
{
src = sources.Current;
}
else
{
done = true;
}
}
catch (Exception ex)
{
done = true;
sources.Dispose();
this.sources = null;
if (delayErrors)
{
ExceptionHelper.AddException(ref errors, ex);
}
else
{
Interlocked.CompareExchange(ref errors, ex, null);
}
continue;
}
if (!done)
{
active++;
SubscribeTo(src);
continue;
}
else
{
sources.Dispose();
this.sources = null;
}
}
var d = done;
var empty = !observers.TryPeek(out var inner);
if (d && empty)
{
Volatile.Write(ref disposed, true);
var ex = Volatile.Read(ref errors);
if (ex != null)
{
downstream.OnError(ex);
}
else
{
downstream.OnCompleted();
}
}
else
if (!empty)
{
var state = inner.GetState();
if (state == 1)
{
downstream.OnNext(inner.value);
observers.TryDequeue(out var _);
active--;
continue;
}
else
if (state == 2)
{
observers.TryDequeue(out var _);
active--;
continue;
}
}
}
missed = Interlocked.Add(ref wip, -missed);
if (missed == 0)
{
break;
}
}
}
19
View Source File : MaybeConcatMapEager.cs
License : Apache License 2.0
Project Creator : akarnokd
License : Apache License 2.0
Project Creator : akarnokd
internal override void Drain()
{
if (Interlocked.Increment(ref wip) != 1)
{
return;
}
var missed = 1;
var observers = this.observers;
var downstream = this.downstream;
var delayErrors = this.delayErrors;
var sources = this.queue;
for (; ; )
{
if (Volatile.Read(ref disposed))
{
while (observers.TryDequeue(out var inner))
{
inner.Dispose();
}
while (sources.TryDequeue(out var _)) ;
}
else
{
if (!delayErrors)
{
var ex = Volatile.Read(ref errors);
if (ex != null)
{
Volatile.Write(ref disposed, true);
downstream.OnError(ex);
DisposableHelper.Dispose(ref upstream);
continue;
}
}
if (!noMoreSources && active < maxConcurrency && !sources.IsEmpty)
{
if (sources.TryDequeue(out var v))
{
var src = default(IMaybeSource<R>);
try
{
src = RequireNonNullRef(mapper(v), "The mapper returned a null IMaybeSource");
}
catch (Exception ex)
{
if (delayErrors)
{
ExceptionHelper.AddException(ref errors, ex);
Volatile.Write(ref done, true);
}
else
{
Interlocked.CompareExchange(ref errors, ex, null);
}
noMoreSources = true;
DisposableHelper.Dispose(ref upstream);
continue;
}
active++;
SubscribeTo(src);
continue;
}
}
var d = Volatile.Read(ref done) && sources.IsEmpty;
var empty = !observers.TryPeek(out var inner);
if (d && empty)
{
Volatile.Write(ref disposed, true);
var ex = Volatile.Read(ref errors);
if (ex != null)
{
downstream.OnError(ex);
}
else
{
downstream.OnCompleted();
}
DisposableHelper.Dispose(ref upstream);
}
else
if (!empty)
{
var state = inner.GetState();
if (state == 1)
{
downstream.OnNext(inner.value);
observers.TryDequeue(out var _);
active--;
continue;
}
else
if (state == 2)
{
observers.TryDequeue(out var _);
active--;
continue;
}
}
}
missed = Interlocked.Add(ref wip, -missed);
if (missed == 0)
{
break;
}
}
}
19
View Source File : MaybeFlatMapMany.cs
License : Apache License 2.0
Project Creator : akarnokd
License : Apache License 2.0
Project Creator : akarnokd
internal override void InnerSuccess(InnerObserver sender, R item)
{
Remove(sender);
if (Volatile.Read(ref wip) == 0 && Interlocked.CompareExchange(ref wip, 1, 0) == 0)
{
downstream.OnNext(item);
Interlocked.Decrement(ref active);
}
else
{
var q = GetOrCreateQueue();
q.Enqueue(item);
Interlocked.Decrement(ref active);
if (Interlocked.Increment(ref wip) != 1)
{
return;
}
}
DrainLoop();
}
19
View Source File : MaybeMerge.cs
License : Apache License 2.0
Project Creator : akarnokd
License : Apache License 2.0
Project Creator : akarnokd
internal override void InnerSuccess(InnerObserver sender, T item)
{
Remove(sender);
if (Volatile.Read(ref wip) == 0 && Interlocked.CompareExchange(ref wip, 1, 0) == 0)
{
downstream.OnNext(item);
if (Interlocked.Decrement(ref active) != 0)
{
if (Interlocked.Decrement(ref wip) == 0)
{
return;
}
}
}
else
{
var q = GetOrCreateQueue();
q.Enqueue(item);
Interlocked.Decrement(ref active);
if (Interlocked.Increment(ref wip) != 1)
{
return;
}
}
DrainLoop();
}
19
View Source File : MaybeFlatMapMany.cs
License : Apache License 2.0
Project Creator : akarnokd
License : Apache License 2.0
Project Creator : akarnokd
internal override void InnerSuccess(InnerObserver sender, R item)
{
Remove(sender);
if (Volatile.Read(ref wip) == 0 && Interlocked.CompareExchange(ref wip, 1, 0) == 0)
{
downstream.OnNext(item);
if (Interlocked.Decrement(ref active) != 0)
{
if (Interlocked.Decrement(ref wip) == 0)
{
return;
}
}
}
else
{
var q = GetOrCreateQueue();
q.Enqueue(item);
Interlocked.Decrement(ref active);
if (Interlocked.Increment(ref wip) != 1)
{
return;
}
}
DrainLoop();
}
19
View Source File : MaybeMerge.cs
License : Apache License 2.0
Project Creator : akarnokd
License : Apache License 2.0
Project Creator : akarnokd
internal override void InnerSuccess(InnerObserver sender, T item)
{
Remove(sender);
if (Volatile.Read(ref wip) == 0 && Interlocked.CompareExchange(ref wip, 1, 0) == 0)
{
downstream.OnNext(item);
Interlocked.Decrement(ref active);
}
else
{
var q = GetOrCreateQueue();
q.Enqueue(item);
Interlocked.Decrement(ref active);
if (Interlocked.Increment(ref wip) != 1)
{
return;
}
}
DrainLoop();
}
19
View Source File : ObservableSourceConcatMapEager.cs
License : Apache License 2.0
Project Creator : akarnokd
License : Apache License 2.0
Project Creator : akarnokd
protected override void InnerConsumed()
{
Interlocked.Increment(ref requested);
DrainBackpressure();
}
19
View Source File : SingleConcatMapEager.cs
License : Apache License 2.0
Project Creator : akarnokd
License : Apache License 2.0
Project Creator : akarnokd
internal override void Drain()
{
if (Interlocked.Increment(ref wip) != 1)
{
return;
}
var missed = 1;
var observers = this.observers;
var downstream = this.downstream;
var delayErrors = this.delayErrors;
var sources = this.queue;
for (; ; )
{
if (Volatile.Read(ref disposed))
{
while (observers.TryDequeue(out var inner))
{
inner.Dispose();
}
while (sources.TryDequeue(out var _)) ;
}
else
{
if (!delayErrors)
{
var ex = Volatile.Read(ref errors);
if (ex != null)
{
Volatile.Write(ref disposed, true);
downstream.OnError(ex);
DisposableHelper.Dispose(ref upstream);
continue;
}
}
if (!noMoreSources && active < maxConcurrency && !sources.IsEmpty)
{
if (sources.TryDequeue(out var v))
{
var src = default(ISingleSource<R>);
try
{
src = RequireNonNullRef(mapper(v), "The mapper returned a null ISingleSource");
}
catch (Exception ex)
{
if (delayErrors)
{
ExceptionHelper.AddException(ref errors, ex);
Volatile.Write(ref done, true);
}
else
{
Interlocked.CompareExchange(ref errors, ex, null);
}
noMoreSources = true;
DisposableHelper.Dispose(ref upstream);
continue;
}
active++;
SubscribeTo(src);
continue;
}
}
var d = Volatile.Read(ref done) && sources.IsEmpty;
var empty = !observers.TryPeek(out var inner);
if (d && empty)
{
Volatile.Write(ref disposed, true);
var ex = Volatile.Read(ref errors);
if (ex != null)
{
downstream.OnError(ex);
}
else
{
downstream.OnCompleted();
}
DisposableHelper.Dispose(ref upstream);
}
else
if (!empty)
{
var state = inner.GetState();
if (state == 1)
{
downstream.OnNext(inner.value);
observers.TryDequeue(out var _);
active--;
continue;
}
else
if (state == 2)
{
observers.TryDequeue(out var _);
active--;
continue;
}
}
}
missed = Interlocked.Add(ref wip, -missed);
if (missed == 0)
{
break;
}
}
}
19
View Source File : SingleConcatEagerEnumerable.cs
License : Apache License 2.0
Project Creator : akarnokd
License : Apache License 2.0
Project Creator : akarnokd
internal override void Drain()
{
if (Interlocked.Increment(ref wip) != 1)
{
return;
}
var missed = 1;
var observers = this.observers;
var downstream = this.downstream;
var delayErrors = this.delayErrors;
var sources = this.sources;
for (; ; )
{
if (Volatile.Read(ref disposed))
{
while (observers.TryDequeue(out var inner))
{
inner.Dispose();
}
if (sources != null)
{
this.sources = null;
sources.Dispose();
}
}
else
{
if (!delayErrors)
{
var ex = Volatile.Read(ref errors);
if (ex != null)
{
Volatile.Write(ref disposed, true);
downstream.OnError(ex);
continue;
}
}
if (active < maxConcurrency && !done)
{
var src = default(ISingleSource<T>);
try
{
if (sources.MoveNext())
{
src = sources.Current;
}
else
{
done = true;
}
}
catch (Exception ex)
{
done = true;
sources.Dispose();
this.sources = null;
if (delayErrors)
{
ExceptionHelper.AddException(ref errors, ex);
}
else
{
Interlocked.CompareExchange(ref errors, ex, null);
}
continue;
}
if (!done)
{
active++;
SubscribeTo(src);
continue;
}
else
{
sources.Dispose();
this.sources = null;
}
}
var d = done;
var empty = !observers.TryPeek(out var inner);
if (d && empty)
{
Volatile.Write(ref disposed, true);
var ex = Volatile.Read(ref errors);
if (ex != null)
{
downstream.OnError(ex);
}
else
{
downstream.OnCompleted();
}
}
else
if (!empty)
{
var state = inner.GetState();
if (state == 1)
{
downstream.OnNext(inner.value);
observers.TryDequeue(out var _);
active--;
continue;
}
else
if (state == 2)
{
observers.TryDequeue(out var _);
active--;
continue;
}
}
}
missed = Interlocked.Add(ref wip, -missed);
if (missed == 0)
{
break;
}
}
}
19
View Source File : TestScheduler.cs
License : Apache License 2.0
Project Creator : akarnokd
License : Apache License 2.0
Project Creator : akarnokd
IDisposable ScheduleActual<TState>(TState state, DateTimeOffset dueTime, Func<IScheduler, TState, IDisposable> action)
{
var key = new TestSchedulerTaskKey(Interlocked.Increment(ref index), dueTime);
Add(key, () => {
key.SetNext(action(this, state));
});
return key;
}
19
View Source File : FlowableGenerate.cs
License : Apache License 2.0
Project Creator : akarnokd
License : Apache License 2.0
Project Creator : akarnokd
public void Cancel()
{
Volatile.Write(ref cancelled, true);
if (Interlocked.Increment(ref requested) == 1)
{
if (Interlocked.CompareExchange(ref once, 1, 0) == 0)
{
stateCleanup?.Invoke(state);
}
}
}
19
View Source File : FlowableInterval.cs
License : Apache License 2.0
Project Creator : akarnokd
License : Apache License 2.0
Project Creator : akarnokd
internal void Run()
{
Interlocked.Increment(ref available);
if (outputFused)
{
DrainFused();
}
else
{
Drain();
}
}
19
View Source File : TimedBlockingExecutor.cs
License : Apache License 2.0
Project Creator : akarnokd
License : Apache License 2.0
Project Creator : akarnokd
internal IDisposable Schedule(Action action, TimeSpan delay)
{
if (Volatile.Read(ref shutdown))
{
return EmptyDisposable.Instance;
}
long due = SchedulerHelper.NowUTC() + (long)delay.TotalMilliseconds;
long id = Interlocked.Increment(ref index);
var tt = new TimedTask(action, due, id, queue);
if (Offer(tt))
{
return tt;
}
return EmptyDisposable.Instance;
}
19
View Source File : TimedBlockingExecutor.cs
License : Apache License 2.0
Project Creator : akarnokd
License : Apache License 2.0
Project Creator : akarnokd
internal IDisposable Schedule(Action action, TimeSpan initialDelay, TimeSpan period)
{
if (Volatile.Read(ref shutdown))
{
return EmptyDisposable.Instance;
}
SequentialDisposable inner = new SequentialDisposable();
SequentialDisposable outer = new SequentialDisposable(inner);
long due = SchedulerHelper.NowUTC() + (long)initialDelay.TotalMilliseconds;
long id = Interlocked.Increment(ref index);
long[] count = { 0 };
Action recursive = null;
recursive = () =>
{
action();
var duePeriod = due + (long)(++count[0] * period.TotalMilliseconds);
var idPeriod = Interlocked.Increment(ref index);
var periodTT = new TimedTask(recursive, duePeriod, idPeriod, queue);
if (Offer(periodTT))
{
outer.Replace(periodTT);
}
};
var tt = new TimedTask(recursive, due, id, queue);
if (Offer(tt))
{
inner.Replace(tt);
return outer;
}
return EmptyDisposable.Instance;
}
19
View Source File : TestExecutor.cs
License : Apache License 2.0
Project Creator : akarnokd
License : Apache License 2.0
Project Creator : akarnokd
long NewId()
{
return Interlocked.Increment(ref id);
}
19
View Source File : BlockingQueueConsumer.cs
License : Apache License 2.0
Project Creator : akarnokd
License : Apache License 2.0
Project Creator : akarnokd
internal bool Offer(Action task)
{
if (Volatile.Read(ref shutdown) == 0)
{
queue.Offer(task);
if (Interlocked.Increment(ref wip) == 1)
{
Monitor.Enter(this);
try
{
Monitor.Pulse(this);
}
finally
{
Monitor.Exit(this);
}
}
return true;
}
return false;
}
19
View Source File : IOExecutorService.cs
License : Apache License 2.0
Project Creator : akarnokd
License : Apache License 2.0
Project Creator : akarnokd
public bool Pick(out SingleThreadedExecutor exec)
{
lock (guard)
{
var q = queue;
if (q == ShutdownQueue)
{
exec = null;
return false;
}
if (q.Poll(out var e))
{
exec = e.executor;
return true;
}
var ex = new SingleThreadedExecutor("IOExecutorWorker-" + Interlocked.Increment(ref index));
executors.Add(ex);
exec = ex;
return true;
}
}
19
View Source File : SingleExecutorService.cs
License : Apache License 2.0
Project Creator : akarnokd
License : Apache License 2.0
Project Creator : akarnokd
public void Start()
{
SingleThreadedExecutor ys = null;
for (;;)
{
var xs = Volatile.Read(ref executor);
if (xs != null)
{
break;
}
if (ys == null)
{
ys = new SingleThreadedExecutor(name + "-" + (Interlocked.Increment(ref index)));
}
if (Interlocked.CompareExchange(ref executor, ys, xs) == xs)
{
break;
}
}
}
19
View Source File : TrampolineExecutorService.cs
License : Apache License 2.0
Project Creator : akarnokd
License : Apache License 2.0
Project Creator : akarnokd
void Drain()
{
if (Interlocked.Increment(ref wip) != 1L)
{
return;
}
var q = queue;
long missed = 1L;
for (;;)
{
while (q.Poll(out InterruptibleAction a))
{
if (Volatile.Read(ref cancelled) != 0)
{
try
{
a.Run();
}
catch
{
// TODO what to do with these?
}
}
}
long w = Volatile.Read(ref wip);
if (w == missed)
{
missed = Interlocked.Add(ref wip, -missed);
if (missed == 0L)
{
break;
}
}
else
{
missed = w;
}
}
}
19
View Source File : CacheStatsCounter.cs
License : MIT License
Project Creator : AlphaYu
License : MIT License
Project Creator : AlphaYu
public void Increment(StatsType statsType)
{
Interlocked.Increment(ref _counters[(int)statsType]);
}
19
View Source File : NatsClient.cs
License : MIT License
Project Creator : AndyPook
License : MIT License
Project Creator : AndyPook
private string GetNextSid() => Interlocked.Increment(ref ssid).ToString(CultureInfo.InvariantCulture);
19
View Source File : AtomicLong.cs
License : Apache License 2.0
Project Creator : apache
License : Apache License 2.0
Project Creator : apache
public long IncrementAndGet()
{
return Interlocked.Increment(ref value);
}
19
View Source File : IdGenerator.cs
License : Apache License 2.0
Project Creator : apache
License : Apache License 2.0
Project Creator : apache
public string GenerateId() => $"{prefix}{Guid.NewGuid().ToString()}:{Interlocked.Increment(ref sequence).ToString()}";
See More Examples