本文整理汇总了C#中System.Threading.ManualResetEventSlim类的典型用法代码示例。如果您正苦于以下问题:C# ManualResetEventSlim类的具体用法?C# ManualResetEventSlim怎么用?C# ManualResetEventSlim使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ManualResetEventSlim类属于System.Threading命名空间,在下文中一共展示了ManualResetEventSlim类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CreateEditorInstance
private static void CreateEditorInstance(EditorTestRequest a, ManualResetEventSlim evt) {
try {
CoreEditor = new CoreEditor(a.Text, a.FileName, a.ContentType);
Window = new Window();
if (Screen.AllScreens.Length == 1) {
Window.Left = 0;
Window.Top = 50;
} else {
Screen secondary = Screen.AllScreens.FirstOrDefault(x => !x.Primary);
Window.Left = secondary.WorkingArea.Left;
Window.Top = secondary.WorkingArea.Top + 50;
}
Window.Width = 800;
Window.Height = 600;
Window.Title = "R Editor - " + (a.FileName ?? "Untitled");
Window.Content = CoreEditor.Control;
} finally {
evt.Set();
}
Window.Topmost = true;
Window.ShowDialog();
}
示例2: CreateWindowInstance
private static void CreateWindowInstance(ControlTestRequest request, ManualResetEventSlim evt) {
try {
Window = new Window();
if (Screen.AllScreens.Length == 1) {
Window.Left = 0;
Window.Top = 50;
} else {
Screen secondary = Screen.AllScreens.FirstOrDefault(x => !x.Primary);
Window.Left = secondary.WorkingArea.Left;
Window.Top = secondary.WorkingArea.Top + 50;
}
Window.Width = 800;
Window.Height = 600;
Component = Activator.CreateInstance(request.ControlType);
if (Component is Control) {
Control = Component as Control;
} else {
Control = Component.GetType().GetProperty("Control").GetValue(Component) as Control;
}
Window.Title = "Control - " + request.ControlType;
Window.Content = Control;
} finally {
evt.Set();
}
Window.Topmost = true;
Window.ShowDialog();
}
示例3: UseSqlNotificationsIfAvailable
public void UseSqlNotificationsIfAvailable(bool supportSqlNotifications)
{
// Arrange
var sqlDependencyAdded = false;
var retryLoopCount = 0;
var mre = new ManualResetEventSlim();
var dbProviderFactory = new MockDbProviderFactory();
var dbBehavior = new Mock<IDbBehavior>();
dbBehavior.Setup(db => db.UpdateLoopRetryDelays).Returns(_defaultRetryDelays);
dbBehavior.Setup(db => db.StartSqlDependencyListener()).Returns(supportSqlNotifications);
dbBehavior.Setup(db => db.AddSqlDependency(It.IsAny<IDbCommand>(), It.IsAny<Action<SqlNotificationEventArgs>>()))
.Callback(() =>
{
sqlDependencyAdded = true;
mre.Set();
});
var operation = new ObservableDbOperation("test", "test", new TraceSource("test"), dbProviderFactory, dbBehavior.Object);
operation.Faulted += _ => mre.Set();
operation.Queried += () =>
{
retryLoopCount++;
if (retryLoopCount > 1)
{
mre.Set();
}
};
// Act
ThreadPool.QueueUserWorkItem(_ => operation.ExecuteReaderWithUpdates((record, o) => { }));
mre.Wait();
operation.Dispose();
// Assert
Assert.Equal(supportSqlNotifications, sqlDependencyAdded);
}
示例4: ConnectRetriesOnError
public async void ConnectRetriesOnError()
{
int invokationCount = 0;
var wh = new ManualResetEventSlim();
var redisConnection = GetMockRedisConnection();
var tcs = new TaskCompletionSource<object>();
tcs.TrySetCanceled();
redisConnection.Setup(m => m.ConnectAsync(It.IsAny<string>(), It.IsAny<TraceSource>())).Returns<string, TraceSource>((connectionString, trace) =>
{
if (++invokationCount == 2)
{
wh.Set();
return Task.FromResult(0);
}
else
{
return tcs.Task;
}
});
var redisMessageBus = new RedisMessageBus(GetDependencyResolver(), new RedisScaleoutConfiguration(String.Empty, String.Empty),
redisConnection.Object, false);
await redisMessageBus.ConnectWithRetry();
Assert.True(wh.Wait(TimeSpan.FromSeconds(5)));
Assert.Equal(RedisMessageBus.State.Connected, redisMessageBus.ConnectionState);
}
示例5: RunConnectDisconnect
public static IDisposable RunConnectDisconnect(int connections)
{
var host = new MemoryHost();
host.MapHubs();
for (int i = 0; i < connections; i++)
{
var connection = new Client.Hubs.HubConnection("http://foo");
var proxy = connection.CreateHubProxy("EchoHub");
var wh = new ManualResetEventSlim(false);
proxy.On("echo", _ => wh.Set());
try
{
connection.Start(host).Wait();
proxy.Invoke("Echo", "foo").Wait();
if (!wh.Wait(TimeSpan.FromSeconds(10)))
{
Debugger.Break();
}
}
finally
{
connection.Stop();
}
}
return host;
}
示例6: Main
static void Main()
{
const int taskCount = 4;
var mEvents = new ManualResetEventSlim[taskCount];
var waitHandles = new WaitHandle[taskCount];
var calcs = new Calculator[taskCount];
for (int i = 0; i < taskCount; i++)
{
int i1 = i;
mEvents[i] = new ManualResetEventSlim(false);
waitHandles[i] = mEvents[i].WaitHandle;
calcs[i] = new Calculator(mEvents[i]);
Task.Run(() => calcs[i1].Calculation(i1 + 1, i1 + 3));
}
for (int i = 0; i < taskCount; i++)
{
// int index = WaitHandle.WaitAny(mEvents.Select(e => e.WaitHandle).ToArray());
int index = WaitHandle.WaitAny(waitHandles);
if (index == WaitHandle.WaitTimeout)
{
WriteLine("Timeout!!");
}
else
{
mEvents[index].Reset();
WriteLine($"finished task for {index}, result: {calcs[index].Result}");
}
}
}
示例7: continuation_error_handling_then_completion
public void continuation_error_handling_then_completion()
{
ManualResetEventSlim first = new ManualResetEventSlim(false),
second = new ManualResetEventSlim(false),
third = new ManualResetEventSlim(false);
Exception ex = null;
// each ContinueWith creates a new task
var t = Task.Factory.StartNew(() =>
{
first.Set();
throw new ApplicationException();
//return -5;
})
.ContinueWith(tStart =>
{
second.Set();
ex = tStart.Exception.InnerExceptions.First();
}, TaskContinuationOptions.NotOnRanToCompletion)
.ContinueWith(tStart => third.Set(), TaskContinuationOptions.OnlyOnRanToCompletion);
t.Wait();
Assert.IsTrue(first.IsSet);
Assert.IsTrue(second.IsSet);
Assert.IsTrue(third.IsSet);
Assert.That(ex, Is.InstanceOf<ApplicationException>());
}
示例8: MetadataRetriever
/// <summary>
/// Creates a new <see cref="MetadataRetriever"/> instance with the specified <paramref name="connectionString"/>.
/// </summary>
/// <param name="connectionString">GEP connection string for openHistorian.</param>
private MetadataRetriever(string connectionString)
{
m_subscriber = new DataSubscriber
{
ConnectionString = connectionString,
ReceiveInternalMetadata = true,
ReceiveExternalMetadata = true
};
m_subscriber.OperationalModes |=
OperationalModes.UseCommonSerializationFormat |
OperationalModes.CompressMetadata |
OperationalModes.CompressSignalIndexCache;
// Attach to needed subscriber events
m_subscriber.ProcessException += m_subscriber_ProcessException;
m_subscriber.ConnectionEstablished += m_subscriber_ConnectionEstablished;
m_subscriber.MetaDataReceived += m_subscriber_MetaDataReceived;
// Initialize the subscriber
m_subscriber.Initialize();
// Create a wait handle to allow time to receive meta-data
m_waitHandle = new ManualResetEventSlim();
// Start subscriber connection cycle
m_subscriber.Start();
}
示例9: State
public State(int count)
{
signals = new ManualResetEventSlim[count];
for (int i = 0; i < signals.Length; i++)
signals[i] = new ManualResetEventSlim(i == 0);
}
示例10: ETradeDispatcher
public ETradeDispatcher(Action<Exception> errorHandler)
: base(errorHandler)
{
const int num = 2; //num of Add() calls below
var count = 0;
var done = new ManualResetEventSlim(false);
Action report = delegate
{
if (Interlocked.Increment(ref count) == num)
done.Set();
};
int idmain, iddom;
idmain = iddom = 0;
Add(() =>
{
idmain = Thread.CurrentThread.ManagedThreadId;
report();
}, _eventThreadRequestName);
Add(() =>
{
iddom = Thread.CurrentThread.ManagedThreadId;
report();
}, _eventThreadResponseName);
done.Wait();
_eventThreadRequestId = idmain;
_eventThreadResponseId = iddom;
}
示例11: When_command_committed_CompletionTaskSource_is_notified
public void When_command_committed_CompletionTaskSource_is_notified()
{
const int CommandCount = 5;
var leader = CreateNetworkAndGetLeader(3);
var commands = Builder<DictionaryCommand.Set>.CreateListOfSize(CommandCount)
.All()
.With(x => x.Completion = new TaskCompletionSource<object>())
.With(x => x.AssignedIndex = -1)
.Build()
.ToList();
var nonLeaderNode = Nodes.First(x => x.State != RaftEngineState.Leader);
var commitsAppliedEvent = new ManualResetEventSlim();
nonLeaderNode.CommitIndexChanged += (oldIndex, newIndex) =>
{
//CommandCount + 1 --> take into account NOP command that leader sends after election
if (newIndex == CommandCount + 1)
commitsAppliedEvent.Set();
};
commands.ForEach(leader.AppendCommand);
Assert.True(commitsAppliedEvent.Wait(nonLeaderNode.Options.ElectionTimeout * 2));
commands.Should().OnlyContain(cmd => cmd.Completion.Task.Status == TaskStatus.RanToCompletion);
}
示例12: Run
public void Run()
{
_pipeHandleSet = new ManualResetEventSlim(initialState: false);
Task.Run(() => Reader());
Task.Run(() => Writer());
}
示例13: FunWithMRE
private static void FunWithMRE()
{
ManualResetEventSlim mre = new ManualResetEventSlim();
//MRE mre = new MRE();
mre.WaitAsync().ContinueWith(t => CW("Wait 1 complete"));
mre.WaitAsync().ContinueWith(t => CW("Wait 2 complete"));
mre.WaitAsync().ContinueWith(t => CW("Wait 3 complete"));
WaitUntilKey("set");
mre.Set();
mre.WaitAsync().ContinueWith(t => CW("Wait 4 complete"));
mre.WaitAsync().ContinueWith(t => CW("Wait 5 complete"));
mre.WaitAsync().ContinueWith(t => CW("Wait 6 complete"));
//WaitUntilKey("reset");
mre.Reset();
mre.WaitAsync().ContinueWith(t => CW("Wait 7 complete"));
mre.WaitAsync().ContinueWith(t => CW("Wait 8 complete"));
mre.WaitAsync().ContinueWith(t => CW("Wait 9 complete"));
WaitUntilKey("set again");
mre.Set();
}
示例14: WebSocket
public WebSocket(DiscordClient client, JsonSerializer serializer, Logger logger)
{
_client = client;
Logger = logger;
_serializer = serializer;
_lock = new AsyncLock();
_taskManager = new TaskManager(Cleanup);
CancelToken = new CancellationToken(true);
_connectedEvent = new ManualResetEventSlim(false);
#if !DOTNET5_4
_engine = new WS4NetEngine(client.Config, _taskManager);
#else
_engine = new BuiltInEngine(client.Config);
#endif
_engine.BinaryMessage += (s, e) =>
{
using (var compressed = new MemoryStream(e.Data, 2, e.Data.Length - 2))
using (var decompressed = new MemoryStream())
{
using (var zlib = new DeflateStream(compressed, CompressionMode.Decompress))
zlib.CopyTo(decompressed);
decompressed.Position = 0;
using (var reader = new StreamReader(decompressed))
ProcessMessage(reader.ReadToEnd()).GetAwaiter().GetResult();
}
};
_engine.TextMessage += (s, e) => ProcessMessage(e.Message).Wait();
}
示例15: MarkActiveStopsConnectionIfCalledAfterExtendedPeriod
public void MarkActiveStopsConnectionIfCalledAfterExtendedPeriod(HostType hostType, TransportType transportType, MessageBusType messageBusType)
{
using (var host = CreateHost(hostType, transportType))
{
host.Initialize(messageBusType: messageBusType);
var connection = CreateHubConnection(host);
using (connection)
{
var disconnectWh = new ManualResetEventSlim();
connection.Closed += () =>
{
disconnectWh.Set();
};
connection.Start(host.Transport).Wait();
// The MarkActive interval should check the reconnect window. Since this is short it should force the connection to disconnect.
((Client.IConnection)connection).ReconnectWindow = TimeSpan.FromSeconds(1);
Assert.True(disconnectWh.Wait(TimeSpan.FromSeconds(15)), "Closed never fired");
}
}
}