本文整理汇总了C#中System.Threading.ManualResetEventSlim类的典型用法代码示例。如果您正苦于以下问题:C# ManualResetEventSlim类的具体用法?C# ManualResetEventSlim怎么用?C# ManualResetEventSlim使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ManualResetEventSlim类属于System.Threading命名空间,在下文中一共展示了ManualResetEventSlim类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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();
}
开发者ID:AlexanderSher,项目名称:RTVS-Old,代码行数:27,代码来源:EditorWindow.cs
示例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();
}
开发者ID:AlexanderSher,项目名称:RTVS-Old,代码行数:32,代码来源:ControlWindow.cs
示例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);
}
开发者ID:Choulla-Naresh8264,项目名称:SignalR,代码行数:35,代码来源:ObservableSqlOperationFacts.cs
示例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);
}
开发者ID:kietnha,项目名称:SignalR,代码行数:30,代码来源:RedisMessageBusFacts.cs
示例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;
}
开发者ID:nonintanon,项目名称:SignalR,代码行数:33,代码来源:StressRuns.cs
示例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}");
}
}
}
开发者ID:ProfessionalCSharp,项目名称:ProfessionalCSharp6,代码行数:34,代码来源:Program.cs
示例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>());
}
开发者ID:haf,项目名称:MassTransit-AzureServiceBus,代码行数:31,代码来源:Scratch.cs
示例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();
}
开发者ID:GridProtectionAlliance,项目名称:openHistorian,代码行数:32,代码来源:MetadataReceiver.cs
示例9: State
public State(int count)
{
signals = new ManualResetEventSlim[count];
for (int i = 0; i < signals.Length; i++)
signals[i] = new ManualResetEventSlim(i == 0);
}
开发者ID:TalarionStudios,项目名称:Talarion,代码行数:7,代码来源:State.cs
示例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;
}
开发者ID:RakotVT,项目名称:StockSharp,代码行数:32,代码来源:ETradeDispatcher.cs
示例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);
}
开发者ID:Degot,项目名称:Rhino.Raft,代码行数:27,代码来源:CommandsTests.cs
示例12: Run
public void Run()
{
_pipeHandleSet = new ManualResetEventSlim(initialState: false);
Task.Run(() => Reader());
Task.Run(() => Writer());
}
开发者ID:ProfessionalCSharp,项目名称:ProfessionalCSharp6,代码行数:7,代码来源:Program.cs
示例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();
}
开发者ID:adbk,项目名称:spikes,代码行数:30,代码来源:Program.cs
示例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();
}
开发者ID:MarlboroTX,项目名称:Discord.Net,代码行数:30,代码来源:WebSocket.cs
示例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");
}
}
}
开发者ID:kietnha,项目名称:SignalR,代码行数:25,代码来源:ConnectionFacts.cs
示例16: Client_with_ipv6_should_connect_to_server_and_signal_appropriate_callbacks
public void Client_with_ipv6_should_connect_to_server_and_signal_appropriate_callbacks()
{
var connected1 = new ManualResetEventSlim(false);
var connected2 = new ManualResetEventSlim(false);
var ex = ServerHelpers.CreateExecutor();
var server = ServerHelpers.CreateServerIPv6();
server.Connected.Subscribe(client =>
{
connected1.Set();
});
server.Started.Subscribe(u =>
{
var client = new SocketClient(ex, true);
client.Connected.Subscribe(_ =>
{
connected2.Set();
});
client.Disconnected.Subscribe(exn =>
{
throw exn;
});
client.Connect(new IPEndPoint(IPAddress.IPv6Loopback, server.BindEndPoint.Port));
});
server.Start();
connected1.AssertWaitFor(5000);
connected2.AssertWaitFor(5000);
server.StopAndAssertStopped();
}
开发者ID:wushian,项目名称:Stacks,代码行数:34,代码来源:RawBytesClientTests.cs
示例17: Respond
public override void Respond(IHttpContext context)
{
if (string.IsNullOrEmpty(context.Request.QueryString["no-op"]) == false)
{
// this is a no-op request which is there just to force the client HTTP layer to handle the authentication
// only used for legacy clients
return;
}
if("generate-single-use-auth-token".Equals(context.Request.QueryString["op"],StringComparison.InvariantCultureIgnoreCase))
{
// using windows auth with anonymous access = none sometimes generate a 401 even though we made two requests
// instead of relying on windows auth, which require request buffering, we generate a one time token and return it.
// we KNOW that the user have access to this db for writing, since they got here, so there is no issue in generating
// a single use token for them.
var token = server.RequestAuthorizer.GenerateSingleUseAuthToken(Database, context.User);
context.WriteJson(new
{
Token = token
});
return;
}
if (HttpContext.Current != null)
{
HttpContext.Current.Server.ScriptTimeout = 60*60*6; // six hours should do it, I think.
}
var options = new BulkInsertOptions
{
CheckForUpdates = context.GetCheckForUpdates(),
CheckReferencesInIndexes = context.GetCheckReferencesInIndexes()
};
var operationId = ExtractOperationId(context);
var sp = Stopwatch.StartNew();
var status = new BulkInsertStatus();
int documents = 0;
var mre = new ManualResetEventSlim(false);
var currentDatbase = Database;
var task = Task.Factory.StartNew(() =>
{
currentDatbase.BulkInsert(options, YieldBatches(context, mre, batchSize => documents += batchSize), operationId);
status.Documents = documents;
status.Completed = true;
});
long id;
Database.AddTask(task, status, out id);
mre.Wait(Database.WorkContext.CancellationToken);
context.Log(log => log.Debug("\tBulk inserted received {0:#,#;;0} documents in {1}, task #: {2}", documents, sp.Elapsed, id));
context.WriteJson(new
{
OperationId = id
});
}
开发者ID:robashton,项目名称:ravendb,代码行数:60,代码来源:BulkInsert.cs
示例18: TcpChannel
protected TcpChannel(int channelId) : base(channelId)
{
_receivingBufferSize = 32 * 1024;
_sendingBlocking = new ManualResetEventSlim(true);
_sendingCounter = new ConcurrentDictionary<long, PackingState>();
_sendingAsyncArgsPool = new SocketAsyncEventArgsPool(SocketAsyncEventArgs_Completed);
}
开发者ID:Flagwind,项目名称:Zongsoft.CoreLibrary,代码行数:7,代码来源:TcpChannel.cs
示例19: be_able_to_subscribe_to_empty_db
public void be_able_to_subscribe_to_empty_db()
{
using (var store = TestConnection.Create(_node.TcpEndPoint))
{
store.ConnectAsync().Wait();
var appeared = new ManualResetEventSlim(false);
var dropped = new CountdownEvent(1);
var subscription = store.SubscribeToAllFrom(null,
false,
(_, x) =>
{
if (!SystemStreams.IsSystemStream(x.OriginalEvent.EventStreamId))
appeared.Set();
},
_ => Log.Info("Live processing started."),
(_, __, ___) => dropped.Signal());
Thread.Sleep(100); // give time for first pull phase
store.SubscribeToAllAsync(false, (s, x) => { }, (s, r, e) => { }).Wait();
Thread.Sleep(100);
Assert.IsFalse(appeared.Wait(0), "Some event appeared.");
Assert.IsFalse(dropped.Wait(0), "Subscription was dropped prematurely.");
subscription.Stop(Timeout);
Assert.IsTrue(dropped.Wait(Timeout));
}
}
开发者ID:danieldeb,项目名称:EventStore,代码行数:28,代码来源:subscribe_to_all_catching_up_should.cs
示例20: ClientStopsReconnectingAfterDisconnectTimeout
public void ClientStopsReconnectingAfterDisconnectTimeout(HostType hostType, TransportType transportType)
{
using (var host = CreateHost(hostType, transportType))
{
host.Initialize(keepAlive: 1, disconnectTimeout: 2);
var connection = new Client.Hubs.HubConnection(host.Url);
var reconnectWh = new ManualResetEventSlim();
var disconnectWh = new ManualResetEventSlim();
connection.Reconnecting += () =>
{
reconnectWh.Set();
Assert.Equal(ConnectionState.Reconnecting, connection.State);
};
connection.Closed += () =>
{
disconnectWh.Set();
Assert.Equal(ConnectionState.Disconnected, connection.State);
};
connection.Start(host.Transport).Wait();
host.Shutdown();
Assert.True(reconnectWh.Wait(TimeSpan.FromSeconds(5)));
Assert.True(disconnectWh.Wait(TimeSpan.FromSeconds(5)));
}
}
开发者ID:rustd,项目名称:SignalR,代码行数:28,代码来源:ConnectionFacts.cs
注:本文中的System.Threading.ManualResetEventSlim类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论