Here are the examples of the csharp api System.Threading.EventWaitHandle.Set() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
3894 Examples
19
Source : CelesteNetClient.cs
with MIT License
from 0x0ade
with MIT License
from 0x0ade
public void Dispose() {
if (!IsAlive)
return;
IsAlive = false;
lock (StartStopLock) {
if (Con == null)
return;
Logger.Log(LogLevel.CRI, "main", "Shutdown");
IsReady = false;
HandshakeEvent.Set();
HandshakeEvent.Dispose();
Con?.Dispose();
Con = null;
Data.Dispose();
}
}
19
Source : RequestQueue.cs
with MIT License
from 0ffffffffh
with MIT License
from 0ffffffffh
public static void Shutdown()
{
//obtain lock to make sure there
//is nobody in the enq/deq op
Log.Info("request queue shutting down");
lock (synchObj)
{
cancelled = true;
Log.Info("Signalling waiter events to finish");
mre.Set();
Requests.Clear();
}
}
19
Source : RequestQueue.cs
with MIT License
from 0ffffffffh
with MIT License
from 0ffffffffh
public static bool Enqueue(RequestObject reqObj)
{
ISozlukRequestHandler handler;
if (cancelled)
return false;
handler = GetHandlerObject(reqObj);
if (handler == null)
return false;
lock (synchObj)
{
Requests.Enqueue(handler);
mre.Set();
}
return true;
}
19
Source : CelesteNetClient.cs
with MIT License
from 0x0ade
with MIT License
from 0x0ade
public void Handle(CelesteNetConnection con, DataHandshakeServer handshake) {
Logger.Log(LogLevel.INF, "main", $"Received handshake: {handshake}");
if (handshake.Version != CelesteNetUtils.Version) {
Dispose();
throw new Exception($"Version mismatch - client {CelesteNetUtils.Version} vs server {handshake.Version}");
}
// Needed because while the server knows the client's TCP endpoint, the UDP endpoint is ambiguous.
if (con is CelesteNetTCPUDPConnection && HandshakeClient is DataHandshakeTCPUDPClient hsClient) {
con.Send(new DataUDPConnectionToken {
Value = hsClient.ConnectionToken
});
}
PlayerInfo = handshake.PlayerInfo;
Data.Handle(con, handshake.PlayerInfo);
HandshakeEvent.Set();
}
19
Source : CelesteNetConnection.cs
with MIT License
from 0x0ade
with MIT License
from 0x0ade
public void Enqueue(DataType data) {
lock (QueueLock) {
int count;
if (MaxCount > 0 && Interlocked.CompareExchange(ref QueueCount, 0, 0) == MaxCount) {
QueueSendNext = (QueueSendNext + 1) % Queue.Length;
} else if ((count = Interlocked.Increment(ref QueueCount)) > Queue.Length) {
count--;
int next = QueueSendNext;
DataType?[] old = Queue;
DataType?[] resized = new DataType?[old.Length * 2];
if (next + count <= old.Length) {
Array.Copy(old, next, resized, 0, count);
} else {
Array.Copy(old, next, resized, 0, old.Length - next);
Array.Copy(old, 0, resized, old.Length - next, count - next);
}
Queue = resized;
QueueSendNext = 0;
QueueAddNext = count;
}
Queue[QueueAddNext] = data;
QueueAddNext = (QueueAddNext + 1) % Queue.Length;
try {
Event.Set();
} catch (ObjectDisposedException) {
}
}
}
19
Source : CelesteNetConnection.cs
with MIT License
from 0x0ade
with MIT License
from 0x0ade
protected virtual void Dispose(bool disposing) {
Buffer.Dispose();
try {
Event.Set();
} catch (ObjectDisposedException) {
}
}
19
Source : UserLock.cs
with Apache License 2.0
from 0xFireball
with Apache License 2.0
from 0xFireball
public void ReleaseExclusiveWrite()
{
// Release exclusive read and write
_writeFree.Set();
_readFree.Set();
}
19
Source : UserLock.cs
with Apache License 2.0
from 0xFireball
with Apache License 2.0
from 0xFireball
public void ReleaseExclusiveRead()
{
_readFree.Set();
}
19
Source : UserLock.cs
with Apache License 2.0
from 0xFireball
with Apache License 2.0
from 0xFireball
public void ReleaseConcurrentRead()
{
// Allow writing again
_writeFree.Set();
}
19
Source : Program.cs
with MIT License
from 2881099
with MIT License
from 2881099
static void Main(string[] args)
{
if (args != null && args.Length == 0) args = new[] { "?" };
ManualResetEvent wait = new ManualResetEvent(false);
new Thread(() => {
Thread.CurrentThread.Join(TimeSpan.FromMilliseconds(10));
try
{
ConsoleApp app = new ConsoleApp(args, wait);
}
finally
{
wait.Set();
}
}).Start();
wait.WaitOne();
return;
}
19
Source : SysProxyHandle.cs
with GNU General Public License v3.0
from 2dust
with GNU General Public License v3.0
from 2dust
private static void ExecSysproxy(string arguments)
{
// using event to avoid hanging when redirect standard output/error
// ref: https://stackoverflow.com/questions/139593/processstartinfo-hanging-on-waitforexit-why
// and http://blog.csdn.net/zhangweixing0/article/details/7356841
using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false))
using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))
{
using (Process process = new Process())
{
// Configure the process using the StartInfo properties.
process.StartInfo.FileName = Utils.GetTempPath("sysproxy.exe");
process.StartInfo.Arguments = arguments;
process.StartInfo.WorkingDirectory = Utils.GetTempPath();
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardOutput = true;
// Need to provide encoding info, or output/error strings we got will be wrong.
process.StartInfo.StandardOutputEncoding = Encoding.Unicode;
process.StartInfo.StandardErrorEncoding = Encoding.Unicode;
process.StartInfo.CreateNoWindow = true;
StringBuilder output = new StringBuilder();
StringBuilder error = new StringBuilder();
process.OutputDataReceived += (sender, e) =>
{
if (e.Data == null)
{
outputWaitHandle.Set();
}
else
{
output.AppendLine(e.Data);
}
};
process.ErrorDataReceived += (sender, e) =>
{
if (e.Data == null)
{
errorWaitHandle.Set();
}
else
{
error.AppendLine(e.Data);
}
};
try
{
process.Start();
process.BeginErrorReadLine();
process.BeginOutputReadLine();
process.WaitForExit();
}
catch (System.ComponentModel.Win32Exception e)
{
// log the arguments
throw new Exception(process.StartInfo.Arguments);
}
string stderr = error.ToString();
string stdout = output.ToString();
int exitCode = process.ExitCode;
if (exitCode != (int)RET_ERRORS.RET_NO_ERROR)
{
throw new Exception(stderr);
}
//if (arguments == "query")
//{
// if (stdout.IsNullOrWhiteSpace() || stdout.IsNullOrEmpty())
// {
// throw new Exception("failed to query wininet settings");
// }
// _queryStr = stdout;
//}
}
}
}
19
Source : RtmpServer.cs
with MIT License
from a1q123456
with MIT License
from a1q123456
private async void AcceptCallback(IAsyncResult ar, CancellationToken ct)
{
Socket listener = (Socket)ar.AsyncState;
Socket client = listener.EndAccept(ar);
client.NoDelay = true;
// Signal the main thread to continue.
_allDone.Set();
IOPipeLine pipe = null;
try
{
pipe = new IOPipeLine(client, _options);
await pipe.StartAsync(ct);
}
catch (TimeoutException)
{
client.Close();
}
catch (Exception e)
{
Console.WriteLine("{0} Message: {1}", e.GetType().ToString(), e.Message);
Console.WriteLine(e.StackTrace);
client.Close();
}
finally
{
pipe?.Dispose();
}
}
19
Source : LogManagerTests.cs
with MIT License
from Abc-Arbitrage
with MIT License
from Abc-Arbitrage
[Test]
public void should_wait_for_event_when_log_event_pool_is_exhausted()
{
LogManager.Shutdown();
BasicConfigurator.Configure(new ZeroLogBasicConfiguration
{
Appenders = { _testAppender },
LogEventQueueSize = 10,
LogEventPoolExhaustionStrategy = LogEventPoolExhaustionStrategy.WaitForLogEvent
});
var log = LogManager.GetLogger(typeof(LogManagerTests));
var actualLogEvents = new List<ILogEvent>();
for (var i = 0; i < 10; i++)
{
actualLogEvents.Add(log.Debug());
}
var signal = _testAppender.SetMessageCountTarget(2);
var logCompletedSignal = new ManualResetEvent(false);
Task.Run(() =>
{
log.Debug().Append("this is not going to happen").Log();
logCompletedSignal.Set();
});
Check.That(logCompletedSignal.WaitOne(TimeSpan.FromMilliseconds(100))).IsFalse();
actualLogEvents[0].Log();
Check.That(logCompletedSignal.WaitOne(TimeSpan.FromMilliseconds(100))).IsTrue();
Check.That(signal.Wait(TimeSpan.FromMilliseconds(100))).IsTrue();
}
19
Source : OVRNetwork.cs
with MIT License
from absurd-joy
with MIT License
from absurd-joy
public void Connect(int listeningPort)
{
if (tcpClient == null)
{
receivedBufferIndex = 0;
receivedBufferDataSize = 0;
readyReceiveDataEvent.Set();
string remoteAddress = "127.0.0.1";
tcpClient = new TcpClient(AddressFamily.InterNetwork);
tcpClient.BeginConnect(remoteAddress, listeningPort, new AsyncCallback(ConnectCallback), tcpClient);
if (connectionStateChangedCallback != null)
{
connectionStateChangedCallback();
}
}
else
{
Debug.LogWarning("[OVRNetworkTcpClient] already connected");
}
}
19
Source : OVRNetwork.cs
with MIT License
from absurd-joy
with MIT License
from absurd-joy
void OnReadDataCallback(IAsyncResult ar)
{
NetworkStream stream = ar.AsyncState as NetworkStream;
try
{
int numBytes = stream.EndRead(ar);
receivedBufferDataSize += numBytes;
while (receivedBufferDataSize >= FrameHeader.StructSize)
{
FrameHeader header = FrameHeader.FromBytes(receivedBuffers[receivedBufferIndex]);
if (header.protocolIdentifier != OVRNetwork.FrameHeaderMagicIdentifier)
{
Debug.LogWarning("[OVRNetworkTcpClient] header mismatch");
Disconnect();
return;
}
if (header.payloadLength < 0 || header.payloadLength > OVRNetwork.MaxPayloadLength)
{
Debug.LogWarningFormat("[OVRNetworkTcpClient] Sanity check failed. PayloadLength %d", header.payloadLength);
Disconnect();
return;
}
if (receivedBufferDataSize >= FrameHeader.StructSize + header.payloadLength)
{
if (payloadReceivedCallback != null)
{
payloadReceivedCallback(header.payloadType, receivedBuffers[receivedBufferIndex], FrameHeader.StructSize, header.payloadLength);
}
// swap receive buffer
int newBufferIndex = 1 - receivedBufferIndex;
int newBufferDataSize = receivedBufferDataSize - (FrameHeader.StructSize + header.payloadLength);
if (newBufferDataSize > 0)
{
Array.Copy(receivedBuffers[receivedBufferIndex], (FrameHeader.StructSize + header.payloadLength), receivedBuffers[newBufferIndex], 0, newBufferDataSize);
}
receivedBufferIndex = newBufferIndex;
receivedBufferDataSize = newBufferDataSize;
}
}
readyReceiveDataEvent.Set();
}
catch (SocketException e)
{
Debug.LogErrorFormat("[OVRNetworkTcpClient] OnReadDataCallback: socket error: {0}", e.Message);
Disconnect();
}
}
19
Source : AudioDeviceHandler.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
private void DataAvailable(object sender, WaveInEventArgs e)
{
if (e.BytesRecorded == 0) return;
// We need to get off this thread ASAP to avoid losing frames
lock (_input)
{
_reader.ReadSamples(e.Buffer, e.BytesRecorded, _input);
_processEvt.Set();
}
}
19
Source : ProcessController.cs
with MIT License
from Accelerider
with MIT License
from Accelerider
public static void Clear()
{
//notify the watch dog by setting the event
if (_keepAliveEvent != null && !_keepAliveEvent.SafeWaitHandle.IsClosed)
{
_keepAliveEvent?.Set();
_keepAliveEvent?.Close();
}
}
19
Source : Runner.cs
with MIT License
from actions
with MIT License
from actions
public async Task<int> ExecuteCommand(CommandSettings command)
{
try
{
VssUtil.InitializeVssClientSettings(HostContext.UserAgents, HostContext.WebProxy);
_inConfigStage = true;
_completedCommand.Reset();
_term.CancelKeyPress += CtrlCHandler;
//register a SIGTERM handler
HostContext.Unloading += Runner_Unloading;
// TODO Unit test to cover this logic
Trace.Info(nameof(ExecuteCommand));
var configManager = HostContext.GetService<IConfigurationManager>();
// command is not required, if no command it just starts if configured
// TODO: Invalid config prints usage
if (command.Help)
{
PrintUsage(command);
return Constants.Runner.ReturnCode.Success;
}
if (command.Version)
{
_term.WriteLine(BuildConstants.RunnerPackage.Version);
return Constants.Runner.ReturnCode.Success;
}
if (command.Commit)
{
_term.WriteLine(BuildConstants.Source.CommitHash);
return Constants.Runner.ReturnCode.Success;
}
if (command.Check)
{
var url = command.GetUrl();
var pat = command.GetGitHubPersonalAccessToken(required: true);
var checkExtensions = HostContext.GetService<IExtensionManager>().GetExtensions<ICheckExtension>();
var sortedChecks = checkExtensions.OrderBy(x => x.Order);
foreach (var check in sortedChecks)
{
_term.WriteLine($"**********************************************************************************************************************");
_term.WriteLine($"** Check: {check.CheckName}");
_term.WriteLine($"** Description: {check.CheckDescription}");
_term.WriteLine($"**********************************************************************************************************************");
var result = await check.RunCheck(url, pat);
if (!result)
{
_term.WriteLine($"** **");
_term.WriteLine($"** F A I L **");
_term.WriteLine($"** **");
_term.WriteLine($"**********************************************************************************************************************");
_term.WriteLine($"** Log: {check.CheckLog}");
_term.WriteLine($"** Help Doc: {check.HelpLink}");
_term.WriteLine($"**********************************************************************************************************************");
}
else
{
_term.WriteLine($"** **");
_term.WriteLine($"** P A S S **");
_term.WriteLine($"** **");
_term.WriteLine($"**********************************************************************************************************************");
_term.WriteLine($"** Log: {check.CheckLog}");
_term.WriteLine($"**********************************************************************************************************************");
}
_term.WriteLine();
_term.WriteLine();
}
return Constants.Runner.ReturnCode.Success;
}
// Configure runner prompt for args if not supplied
// Unattended configure mode will not prompt for args if not supplied and error on any missing or invalid value.
if (command.Configure)
{
try
{
await configManager.ConfigureAsync(command);
return Constants.Runner.ReturnCode.Success;
}
catch (Exception ex)
{
Trace.Error(ex);
_term.WriteError(ex.Message);
return Constants.Runner.ReturnCode.TerminatedError;
}
}
// remove config files, remove service, and exit
if (command.Remove)
{
try
{
await configManager.UnconfigureAsync(command);
return Constants.Runner.ReturnCode.Success;
}
catch (Exception ex)
{
Trace.Error(ex);
_term.WriteError(ex.Message);
return Constants.Runner.ReturnCode.TerminatedError;
}
}
_inConfigStage = false;
// warmup runner process (JIT/CLR)
// In scenarios where the runner is single use (used and then thrown away), the system provisioning the runner can call `Runner.Listener --warmup` before the machine is made available to the pool for use.
// this will optimizes the runner process startup time.
if (command.Warmup)
{
var binDir = HostContext.GetDirectory(WellKnownDirectory.Bin);
foreach (var replacedemblyFile in Directory.EnumerateFiles(binDir, "*.dll"))
{
try
{
Trace.Info($"Load replacedembly: {replacedemblyFile}.");
var replacedembly = replacedembly.LoadFrom(replacedemblyFile);
var types = replacedembly.GetTypes();
foreach (Type loadedType in types)
{
try
{
Trace.Info($"Load methods: {loadedType.FullName}.");
var methods = loadedType.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
foreach (var method in methods)
{
if (!method.IsAbstract && !method.ContainsGenericParameters)
{
Trace.Verbose($"Prepare method: {method.Name}.");
RuntimeHelpers.PrepareMethod(method.MethodHandle);
}
}
}
catch (Exception ex)
{
Trace.Error(ex);
}
}
}
catch (Exception ex)
{
Trace.Error(ex);
}
}
return Constants.Runner.ReturnCode.Success;
}
RunnerSettings settings = configManager.LoadSettings();
var store = HostContext.GetService<IConfigurationStore>();
bool configuredreplacedervice = store.IsServiceConfigured();
// Run runner
if (command.Run) // this line is current break machine provisioner.
{
// Error if runner not configured.
if (!configManager.IsConfigured())
{
_term.WriteError("Runner is not configured.");
PrintUsage(command);
return Constants.Runner.ReturnCode.TerminatedError;
}
Trace.Verbose($"Configured as service: '{configuredreplacedervice}'");
//Get the startup type of the runner i.e., autostartup, service, manual
StartupType startType;
var startupTypereplacedtring = command.GetStartupType();
if (string.IsNullOrEmpty(startupTypereplacedtring) && configuredreplacedervice)
{
// We need try our best to make the startup type accurate
// The problem is coming from runner autoupgrade, which result an old version service host binary but a newer version runner binary
// At that time the servicehost won't preplaced --startuptype to Runner.Listener while the runner is actually running as service.
// We will guess the startup type only when the runner is configured as service and the guess will based on whether STDOUT/STDERR/STDIN been redirect or not
Trace.Info($"Try determine runner startup type base on console redirects.");
startType = (Console.IsErrorRedirected && Console.IsInputRedirected && Console.IsOutputRedirected) ? StartupType.Service : StartupType.Manual;
}
else
{
if (!Enum.TryParse(startupTypereplacedtring, true, out startType))
{
Trace.Info($"Could not parse the argument value '{startupTypereplacedtring}' for StartupType. Defaulting to {StartupType.Manual}");
startType = StartupType.Manual;
}
}
Trace.Info($"Set runner startup type - {startType}");
HostContext.StartupType = startType;
if (command.RunOnce)
{
_term.WriteLine("Warning: '--once' is going to be deprecated in the future, please consider using '--ephemeral' during runner registration.", ConsoleColor.Yellow);
_term.WriteLine("https://docs.github.com/en/actions/hosting-your-own-runners/autoscaling-with-self-hosted-runners#using-ephemeral-runners-for-autoscaling", ConsoleColor.Yellow);
}
// Run the runner interactively or as service
return await RunAsync(settings, command.RunOnce || settings.Ephemeral);
}
else
{
PrintUsage(command);
return Constants.Runner.ReturnCode.Success;
}
}
finally
{
_term.CancelKeyPress -= CtrlCHandler;
HostContext.Unloading -= Runner_Unloading;
_completedCommand.Set();
}
}
19
Source : Worker.cs
with MIT License
from actions
with MIT License
from actions
public async Task<int> RunAsync(string pipeIn, string pipeOut)
{
try
{
// Setup way to handle SIGTERM/unloading signals
_completedCommand.Reset();
HostContext.Unloading += Worker_Unloading;
// Validate args.
ArgUtil.NotNullOrEmpty(pipeIn, nameof(pipeIn));
ArgUtil.NotNullOrEmpty(pipeOut, nameof(pipeOut));
VssUtil.InitializeVssClientSettings(HostContext.UserAgents, HostContext.WebProxy);
var jobRunner = HostContext.CreateService<IJobRunner>();
using (var channel = HostContext.CreateService<IProcessChannel>())
using (var jobRequestCancellationToken = CancellationTokenSource.CreateLinkedTokenSource(HostContext.RunnerShutdownToken))
using (var channelTokenSource = new CancellationTokenSource())
{
// Start the channel.
channel.StartClient(pipeIn, pipeOut);
// Wait for up to 30 seconds for a message from the channel.
HostContext.WritePerfCounter("WorkerWaitingForJobMessage");
Trace.Info("Waiting to receive the job message from the channel.");
WorkerMessage channelMessage;
using (var csChannelMessage = new CancellationTokenSource(_workerStartTimeout))
{
channelMessage = await channel.ReceiveAsync(csChannelMessage.Token);
}
// Deserialize the job message.
Trace.Info("Message received.");
ArgUtil.Equal(MessageType.NewJobRequest, channelMessage.MessageType, nameof(channelMessage.MessageType));
ArgUtil.NotNullOrEmpty(channelMessage.Body, nameof(channelMessage.Body));
var jobMessage = StringUtil.ConvertFromJson<Pipelines.AgentJobRequestMessage>(channelMessage.Body);
ArgUtil.NotNull(jobMessage, nameof(jobMessage));
HostContext.WritePerfCounter($"WorkerJobMessageReceived_{jobMessage.RequestId.ToString()}");
// Initialize the secret masker and set the thread culture.
InitializeSecretMasker(jobMessage);
SetCulture(jobMessage);
// Start the job.
Trace.Info($"Job message:{Environment.NewLine} {StringUtil.ConvertToJson(jobMessage)}");
Task<TaskResult> jobRunnerTask = jobRunner.RunAsync(jobMessage, jobRequestCancellationToken.Token);
// Start listening for a cancel message from the channel.
Trace.Info("Listening for cancel message from the channel.");
Task<WorkerMessage> channelTask = channel.ReceiveAsync(channelTokenSource.Token);
// Wait for one of the tasks to complete.
Trace.Info("Waiting for the job to complete or for a cancel message from the channel.");
Task.WaitAny(jobRunnerTask, channelTask);
// Handle if the job completed.
if (jobRunnerTask.IsCompleted)
{
Trace.Info("Job completed.");
channelTokenSource.Cancel(); // Cancel waiting for a message from the channel.
return TaskResultUtil.TranslateToReturnCode(await jobRunnerTask);
}
// Otherwise a cancel message was received from the channel.
Trace.Info("Cancellation/Shutdown message received.");
channelMessage = await channelTask;
switch (channelMessage.MessageType)
{
case MessageType.CancelRequest:
jobRequestCancellationToken.Cancel(); // Expire the host cancellation token.
break;
case MessageType.RunnerShutdown:
HostContext.ShutdownRunner(ShutdownReason.UserCancelled);
break;
case MessageType.OperatingSystemShutdown:
HostContext.ShutdownRunner(ShutdownReason.OperatingSystemShutdown);
break;
default:
throw new ArgumentOutOfRangeException(nameof(channelMessage.MessageType), channelMessage.MessageType, nameof(channelMessage.MessageType));
}
// Await the job.
return TaskResultUtil.TranslateToReturnCode(await jobRunnerTask);
}
}
finally
{
HostContext.Unloading -= Worker_Unloading;
_completedCommand.Set();
}
}
19
Source : WebViewRender.cs
with MIT License
from adamped
with MIT License
from adamped
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
{
base.OnElementChanged(e);
var oldWebView = e.OldElement as WebViewer;
if (oldWebView != null)
oldWebView.EvaluateJavascript = null;
var newWebView = e.NewElement as WebViewer;
if (newWebView != null)
newWebView.EvaluateJavascript = async (js) =>
{
ManualResetEvent reset = new ManualResetEvent(false);
var response = "";
Device.BeginInvokeOnMainThread(() =>
{
System.Diagnostics.Debug.WriteLine("Javascript Send: " + js);
Control?.EvaluateJavascript(js, new JavascriptCallback((r) => { response = r; reset.Set(); }));
});
await Task.Run(() => { reset.WaitOne(); });
if (response == "null")
response = string.Empty;
return response;
};
if (Control != null && e.NewElement != null)
{
InitializeCommands((WebViewer)e.NewElement);
SetupControl();
}
}
19
Source : Parallel.cs
with MIT License
from adrenak
with MIT License
from adrenak
public void Terminate() {
this.taskWaiting.Set();
this.thread.Join();
this.taskWaiting.Close();
this.threadIdle.Close();
}
19
Source : Parallel.cs
with MIT License
from adrenak
with MIT License
from adrenak
public void DoFor(int start, int stop, ForLoopDelegate loopBody) {
this.currentJobIndex = start - 1;
this.stopIndex = stop;
this.LoopFunction = loopBody;
// Signal waiting task to all threads and mark them not idle.
for (int i = 0; i < this.threadCount; i++) {
WorkerThread workerThread = workerThreads[i];
workerThread.ThreadIdle.Reset();
workerThread.TaskWaiting.Set();
}
// Wait until all threads become idle
for (int i = 0; i < this.threadCount; i++) {
WorkerThread workerThread = workerThreads[i];
workerThread.ThreadIdle.WaitOne();
}
}
19
Source : Parallel.cs
with MIT License
from adrenak
with MIT License
from adrenak
private void RunWorkerThread(object threadIndex) {
WorkerThread workerThread = workerThreads[(int)threadIndex];
int localJobIndex = 0;
while (true) {
// Wait for a task.
workerThread.TaskWaiting.WaitOne();
// Exit if task is empty.
if (LoopFunction == null) {
return;
}
localJobIndex = Interlocked.Increment(ref currentJobIndex);
while (localJobIndex < stopIndex) {
////Console.WriteLine("Thread " + threadIndex + " of " + workerThreads.Count + " running task " + localJobIndex);
LoopFunction(localJobIndex);
localJobIndex = Interlocked.Increment(ref currentJobIndex);
}
// Signal that thread is idle.
workerThread.ThreadIdle.Set();
}
}
19
Source : Parallel.cs
with MIT License
from adrenak
with MIT License
from adrenak
public void DoForEach(IEnumerable<T> items, ForEachLoopDelegate loopBody) {
this.enumerator = items.GetEnumerator();
this.LoopFunction = loopBody;
// Signal waiting task to all threads and mark them not idle.
for (int i = 0; i < this.threadCount; i++) {
WorkerThread workerThread = workerThreads[i];
workerThread.ThreadIdle.Reset();
workerThread.TaskWaiting.Set();
}
// Wait until all threads become idle
for (int i = 0; i < this.threadCount; i++) {
WorkerThread workerThread = workerThreads[i];
workerThread.ThreadIdle.WaitOne();
}
}
19
Source : Parallel.cs
with MIT License
from adrenak
with MIT License
from adrenak
private void RunWorkerThread(object threadIndex) {
WorkerThread workerThread = workerThreads[(int)threadIndex];
while (true) {
// Wait for a task.
workerThread.TaskWaiting.WaitOne();
// Exit if task is empty.
if (LoopFunction == null) {
return;
}
bool didMoveNext;
T localItem = default(T);
lock (this.enumerator) {
didMoveNext = enumerator.MoveNext();
if (didMoveNext) {
localItem = enumerator.Current;
}
}
while (didMoveNext == true) {
////Console.WriteLine("Thread " + threadIndex + " of " + workerThreads.Count + " running task " + localJobIndex);
LoopFunction(localItem);
lock (this.enumerator) {
didMoveNext = enumerator.MoveNext();
if (didMoveNext) {
localItem = enumerator.Current;
}
}
}
// Signal that thread is idle.
workerThread.ThreadIdle.Set();
}
}
19
Source : ThreadPool.cs
with MIT License
from adrenak
with MIT License
from adrenak
private void EnqueueTask(WaitCallback callback, object state) {
while (m_numTasks == m_taskQueue.Length) {
m_getNotification.WaitOne();
}
m_taskQueue[m_nPutPointer].callback = callback;
m_taskQueue[m_nPutPointer].args = state;
++m_nPutPointer;
if (m_nPutPointer == m_taskQueue.Length) {
m_nPutPointer = 0;
}
#if !UNITY_WEBGL
if (m_threadPool.Length == 1) {
#endif
if (Interlocked.Increment(ref m_numTasks) == 1) {
m_putNotification.Set();
}
#if !UNITY_WEBGL
}
else {
Interlocked.Increment(ref m_numTasks);
m_semapreplaced.Release();
}
#endif
}
19
Source : ThreadPool.cs
with MIT License
from adrenak
with MIT License
from adrenak
private void ThreadFunc() {
for (;;) {
m_semapreplaced.WaitOne();
int nCurrentPointer, nNextPointer;
do {
nCurrentPointer = m_nGetPointer;
nNextPointer = nCurrentPointer + 1;
if (nNextPointer == m_taskQueue.Length) {
nNextPointer = 0;
}
} while (Interlocked.CompareExchange(ref m_nGetPointer, nNextPointer, nCurrentPointer) != nCurrentPointer);
TaskInfo task = m_taskQueue[nCurrentPointer];
if (Interlocked.Decrement(ref m_numTasks) == m_taskQueue.Length - 1) {
m_getNotification.Set();
}
task.callback(task.args);
}
}
19
Source : ThreadPool.cs
with MIT License
from adrenak
with MIT License
from adrenak
private void SingleThreadFunc() {
for (;;) {
while (m_numTasks == 0) {
m_putNotification.WaitOne();
}
TaskInfo task = m_taskQueue[m_nGetPointer++];
if (m_nGetPointer == m_taskQueue.Length) {
m_nGetPointer = 0;
}
if (Interlocked.Decrement(ref m_numTasks) == m_taskQueue.Length - 1) {
m_getNotification.Set();
}
task.callback(task.args);
}
}
19
Source : Parallel.cs
with MIT License
from adrenak
with MIT License
from adrenak
public void Terminate() {
this.taskWaiting.Set();
this.thread.Join();
this.taskWaiting.Close();
this.threadIdle.Close();
}
19
Source : Parallel.cs
with MIT License
from adrenak
with MIT License
from adrenak
public void DoFor(int start, int stop, ForLoopDelegate loopBody) {
this.currentJobIndex = start - 1;
this.stopIndex = stop;
this.LoopFunction = loopBody;
// Signal waiting task to all threads and mark them not idle.
for(int i = 0; i < this.threadCount; i++) {
WorkerThread workerThread = workerThreads[i];
workerThread.ThreadIdle.Reset();
workerThread.TaskWaiting.Set();
}
// Wait until all threads become idle
for(int i = 0; i < this.threadCount; i++) {
WorkerThread workerThread = workerThreads[i];
workerThread.ThreadIdle.WaitOne();
}
}
19
Source : Parallel.cs
with MIT License
from adrenak
with MIT License
from adrenak
private void RunWorkerThread(object threadIndex) {
WorkerThread workerThread = workerThreads[(int)threadIndex];
int localJobIndex = 0;
while(true) {
// Wait for a task.
workerThread.TaskWaiting.WaitOne();
// Exit if task is empty.
if(LoopFunction == null) {
return;
}
localJobIndex = Interlocked.Increment(ref currentJobIndex);
while(localJobIndex < stopIndex) {
////Console.WriteLine("Thread " + threadIndex + " of " + workerThreads.Count + " running task " + localJobIndex);
LoopFunction(localJobIndex);
localJobIndex = Interlocked.Increment(ref currentJobIndex);
}
// Signal that thread is idle.
workerThread.ThreadIdle.Set();
}
}
19
Source : Parallel.cs
with MIT License
from adrenak
with MIT License
from adrenak
public void DoForEach(IEnumerable<T> items, ForEachLoopDelegate loopBody) {
this.enumerator = items.GetEnumerator();
this.LoopFunction = loopBody;
// Signal waiting task to all threads and mark them not idle.
for(int i = 0; i < this.threadCount; i++) {
WorkerThread workerThread = workerThreads[i];
workerThread.ThreadIdle.Reset();
workerThread.TaskWaiting.Set();
}
// Wait until all threads become idle
for(int i = 0; i < this.threadCount; i++) {
WorkerThread workerThread = workerThreads[i];
workerThread.ThreadIdle.WaitOne();
}
}
19
Source : Parallel.cs
with MIT License
from adrenak
with MIT License
from adrenak
private void RunWorkerThread(object threadIndex) {
WorkerThread workerThread = workerThreads[(int)threadIndex];
while(true) {
// Wait for a task.
workerThread.TaskWaiting.WaitOne();
// Exit if task is empty.
if(LoopFunction == null) {
return;
}
bool didMoveNext;
T localItem = default(T);
lock (this.enumerator) {
didMoveNext = enumerator.MoveNext();
if(didMoveNext) {
localItem = enumerator.Current;
}
}
while(didMoveNext == true) {
////Console.WriteLine("Thread " + threadIndex + " of " + workerThreads.Count + " running task " + localJobIndex);
LoopFunction(localItem);
lock (this.enumerator) {
didMoveNext = enumerator.MoveNext();
if(didMoveNext) {
localItem = enumerator.Current;
}
}
}
// Signal that thread is idle.
workerThread.ThreadIdle.Set();
}
}
19
Source : Parallel.cs
with MIT License
from adrenak
with MIT License
from adrenak
public void Terminate()
{
this.taskWaiting.Set();
this.thread.Join();
this.taskWaiting.Close();
this.threadIdle.Close();
}
19
Source : Parallel.cs
with MIT License
from adrenak
with MIT License
from adrenak
public void DoFor(int start, int stop, ForLoopDelegate loopBody)
{
this.currentJobIndex = start - 1;
this.stopIndex = stop;
this.LoopFunction = loopBody;
// Signal waiting task to all threads and mark them not idle.
for (int i = 0; i < this.threadCount; i++)
{
WorkerThread workerThread = workerThreads[i];
workerThread.ThreadIdle.Reset();
workerThread.TaskWaiting.Set();
}
// Wait until all threads become idle
for (int i = 0; i < this.threadCount; i++)
{
WorkerThread workerThread = workerThreads[i];
workerThread.ThreadIdle.WaitOne();
}
}
19
Source : Parallel.cs
with MIT License
from adrenak
with MIT License
from adrenak
private void RunWorkerThread(object threadIndex)
{
WorkerThread workerThread = workerThreads[(int)threadIndex];
int localJobIndex = 0;
while (true)
{
// Wait for a task.
workerThread.TaskWaiting.WaitOne();
// Exit if task is empty.
if (LoopFunction == null)
{
return;
}
localJobIndex = Interlocked.Increment(ref currentJobIndex);
while (localJobIndex < stopIndex)
{
////Console.WriteLine("Thread " + threadIndex + " of " + workerThreads.Count + " running task " + localJobIndex);
LoopFunction(localJobIndex);
localJobIndex = Interlocked.Increment(ref currentJobIndex);
}
// Signal that thread is idle.
workerThread.ThreadIdle.Set();
}
}
19
Source : Parallel.cs
with MIT License
from adrenak
with MIT License
from adrenak
public void DoForEach(IEnumerable<T> items, ForEachLoopDelegate loopBody)
{
this.enumerator = items.GetEnumerator();
this.LoopFunction = loopBody;
// Signal waiting task to all threads and mark them not idle.
for (int i = 0; i < this.threadCount; i++)
{
WorkerThread workerThread = workerThreads[i];
workerThread.ThreadIdle.Reset();
workerThread.TaskWaiting.Set();
}
// Wait until all threads become idle
for (int i = 0; i < this.threadCount; i++)
{
WorkerThread workerThread = workerThreads[i];
workerThread.ThreadIdle.WaitOne();
}
}
19
Source : Parallel.cs
with MIT License
from adrenak
with MIT License
from adrenak
private void RunWorkerThread(object threadIndex)
{
WorkerThread workerThread = workerThreads[(int)threadIndex];
while (true)
{
// Wait for a task.
workerThread.TaskWaiting.WaitOne();
// Exit if task is empty.
if (LoopFunction == null)
{
return;
}
bool didMoveNext;
T localItem = default(T);
lock (this.enumerator)
{
didMoveNext = enumerator.MoveNext();
if (didMoveNext)
{
localItem = enumerator.Current;
}
}
while (didMoveNext == true)
{
////Console.WriteLine("Thread " + threadIndex + " of " + workerThreads.Count + " running task " + localJobIndex);
LoopFunction(localItem);
lock (this.enumerator)
{
didMoveNext = enumerator.MoveNext();
if (didMoveNext)
{
localItem = enumerator.Current;
}
}
}
// Signal that thread is idle.
workerThread.ThreadIdle.Set();
}
}
19
Source : UdpSocket.cs
with Apache License 2.0
from advancer68
with Apache License 2.0
from advancer68
void ReceiveCallback(IAsyncResult ar)
{
Byte[] data = (mIPEndPoint == null) ?
mUdpClient.Receive(ref mIPEndPoint) :
mUdpClient.EndReceive(ar, ref mIPEndPoint);
if (null != data)
{
var dt = new ByteBuf(data);
rcv_queue.Enqueue(dt);
kcpThreadNotify.Set();
}
if (mUdpClient != null)
{
// try to receive again.
mUdpClient.BeginReceive(ReceiveCallback, this);
}
}
19
Source : UdpSocket.cs
with Apache License 2.0
from advancer68
with Apache License 2.0
from advancer68
public void Send(byte[] data)
{
var btBuf = Pack(data);
snd_queue.Enqueue(btBuf);
kcpThreadNotify.Set();
}
19
Source : Model.cs
with MIT License
from advancedmonitoring
with MIT License
from advancedmonitoring
public static void OnClose()
{
if (!TextChangedEvent.WaitOne(0))
TextChangedEvent.Set();
}
19
Source : UIPerformWorkWindow.xaml.cs
with MIT License
from advancedmonitoring
with MIT License
from advancedmonitoring
private void Window_OnClose(object sender, CancelEventArgs e)
{
DialogResult = true;
AbortEvent.Set();
}
19
Source : MainWindow.xaml.cs
with MIT License
from advancedmonitoring
with MIT License
from advancedmonitoring
private void ContentUpdate(object obj)
{
var t = (Tuple<string, UIPerformWorkWindow>) obj;
Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => { EdtContent.Text = ""; }));
var content = t.Item1.Substring(0, t.Item1.Length - 1);
var last = t.Item1.Substring(content.Length);
var all = content.Length + 1;
var setted = 0;
while (content.Length > CONTENT_CHUNK_SIZE)
{
Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action<string>((x) => { EdtContent.AppendText(x); }), content.Substring(0, CONTENT_CHUNK_SIZE));
content = content.Substring(CONTENT_CHUNK_SIZE);
setted += CONTENT_CHUNK_SIZE;
t.Item2.Percentage = (int) ((setted + 0.0) * 100 / (all + 0.0));
if (t.Item2.AbortEvent.WaitOne(0))
{
Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => { EdtContent.TextChanged += EdtContent_OnTextChanged; }));
Thread.CurrentThread.Abort();
return;
}
}
if (content.Length > 0)
Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action<string>((x) => { EdtContent.AppendText(x); }), content);
Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action<string>((x) => { EdtContent.TextChanged += EdtContent_OnTextChanged; EdtContent.AppendText(x); }), last);
var wait = new ManualResetEvent(false);
Dispatcher.BeginInvoke(DispatcherPriority.ContextIdle, new Action<ManualResetEvent>((x) => { x.Set(); }), wait);
wait.WaitOne();
t.Item2.AbortEvent.Set();
Thread.CurrentThread.Abort();
}
19
Source : Model.cs
with MIT License
from advancedmonitoring
with MIT License
from advancedmonitoring
public static void TextChangedContentEdit()
{
if (_textChangedThread != null && _textChangedThread.IsAlive)
{
TextChangedEvent.Set();
_textChangedThread.Join();
}
TextChangedEvent.Reset();
_textChangedThread = new Thread(TextChangedFunc);
_textChangedThread.Start(MW.GetContent());
_textChangedSpinnerThread = new Thread(TextChangedSpinnerFunc);
_textChangedSpinnerThread.Start();
}
19
Source : Model.cs
with MIT License
from advancedmonitoring
with MIT License
from advancedmonitoring
private static void TextChangedFunc(object o)
{
var data = (string)o;
var lines = data.Split('\r', '\n');
var allSIDs = new List<string>();
var allRights = new List<string>();
var prevSids = 0;
var prevRights = 0;
foreach (var line in lines)
{
if (!string.IsNullOrWhiteSpace(line))
{
var sd = new SecurityDescriptor(line.Trim());
if (!sd.IsOk)
continue;
var lSIDs = sd.GetAllSIDs();
foreach (var sid in lSIDs)
if (!allSIDs.Contains(sid))
allSIDs.Add(sid);
var lRights = sd.GetAllRights();
foreach (var right in lRights)
if (!allRights.Contains(right))
allRights.Add(right);
if (allSIDs.Count != prevSids)
{
prevSids = allSIDs.Count;
var sortedSIDs = allSIDs.OrderBy(q => q[1] == '-' ? "ZZ" + q : q).ToList();
MW.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action<List<string>>((x) =>
{
MW.SIDList.Clear();
foreach (var sid in x)
MW.SIDList.Add(new BoolStringClreplaced(SecurityDescriptor.SIDToLong(sid, MW.IsTranslateSID), sid));
}), sortedSIDs);
}
if (allRights.Count != prevRights)
{
prevRights = allRights.Count;
MW.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
{
var newRightsList = new ObservableCollection<BoolStringClreplaced>();
foreach (var element in MW.RightsList)
{
if (allRights.Contains(element.Tag))
element.TextBrush = new SolidColorBrush(Color.FromRgb(50, 150, 255));
newRightsList.Add(element);
}
MW.RightsList.Clear();
foreach (var element in newRightsList)
MW.RightsList.Add(element);
}));
}
}
if (TextChangedEvent.WaitOne(0))
{
if (_textChangedSpinnerThread != null && _textChangedSpinnerThread.IsAlive)
_textChangedSpinnerThread.Join();
Thread.CurrentThread.Abort();
return;
}
}
TextChangedEvent.Set();
if (_textChangedSpinnerThread != null && _textChangedSpinnerThread.IsAlive)
_textChangedSpinnerThread.Join();
Thread.CurrentThread.Abort();
}
19
Source : KoiInfo.cs
with GNU General Public License v3.0
from Aekras1a
with GNU General Public License v3.0
from Aekras1a
private static void CheckUpdate(ConfuserContext ctx)
{
var ver = new KoiSystem().GetVersion(settings.KoiID);
if(ver == settings.Version)
return;
ctx.Logger.LogFormat("New version of KoiVM: {0}", ver);
ctx.Logger.LogFormat("Current version of KoiVM: {0}", settings.Version);
if(settings.NoUI)
{
ctx.Logger.LogFormat("Updating...");
var sys = new KoiSystem();
var hnd = new ManualResetEvent(false);
var okay = false;
sys.Progress += _ => { };
sys.Finish += f =>
{
okay = f;
hnd.Set();
};
sys.Login(settings.KoiID);
hnd.WaitOne();
if(!okay)
throw new InvalidOperationException("Authentication failed.");
settings.Version = ver;
settings.Save();
}
else
{
Application.EnableVisualStyles();
if(new UpdatePrompt(ver) {TopLevel = true}.ShowDialog() != DialogResult.OK)
throw new InvalidOperationException("Authentication failed.");
}
}
19
Source : KoiInfo.cs
with GNU General Public License v3.0
from Aekras1a
with GNU General Public License v3.0
from Aekras1a
private static void RetrieveKoi(ConfuserContext ctx)
{
if(settings.NoUI)
{
ctx.Logger.Log("Retrieving Koi...");
var sys = new KoiSystem();
var hnd = new ManualResetEvent(false);
var okay = false;
sys.Progress += _ => { };
sys.Finish += f =>
{
okay = f;
hnd.Set();
};
sys.Login(settings.KoiID);
hnd.WaitOne();
if(!okay)
throw new InvalidOperationException("Authentication failed.");
}
else
{
Application.EnableVisualStyles();
if(new LoginPrompt {TopLevel = true}.ShowDialog() != DialogResult.OK)
throw new InvalidOperationException("Authentication failed.");
}
}
19
Source : GrpcPeerTests.cs
with MIT License
from AElfProject
with MIT License
from AElfProject
[Fact]
public void EnqueueBlock_ShouldExecuteCallback_Test()
{
AutoResetEvent executed = new AutoResetEvent(false);
NetworkException exception = null;
bool called = false;
_nonInterceptedPeer.EnqueueBlock(new BlockWithTransactions(), ex =>
{
exception = ex;
called = true;
executed.Set();
});
executed.WaitOne();
exception.ShouldBeNull();
called.ShouldBeTrue();
}
19
Source : GrpcPeerTests.cs
with MIT License
from AElfProject
with MIT License
from AElfProject
[Fact]
public void EnqueueTransaction_ShouldExecuteCallback_Test()
{
AutoResetEvent executed = new AutoResetEvent(false);
NetworkException exception = null;
var transaction = new Transaction();
bool called = false;
_nonInterceptedPeer.EnqueueTransaction(transaction, ex =>
{
exception = ex;
called = true;
executed.Set();
});
executed.WaitOne();
exception.ShouldBeNull();
called.ShouldBeTrue();
}
19
Source : GrpcPeerTests.cs
with MIT License
from AElfProject
with MIT License
from AElfProject
[Fact]
public void EnqueueAnnouncement_ShouldExecuteCallback_Test()
{
AutoResetEvent executed = new AutoResetEvent(false);
NetworkException exception = null;
var called = false;
_nonInterceptedPeer.EnqueueAnnouncement(new BlockAnnouncement(), ex =>
{
exception = ex;
called = true;
executed.Set();
});
executed.WaitOne();
exception.ShouldBeNull();
called.ShouldBeTrue();
}
See More Examples