本文整理汇总了C#中System.Threading.ManualResetEvent.Set方法的典型用法代码示例。如果您正苦于以下问题:C# ManualResetEvent.Set方法的具体用法?C# ManualResetEvent.Set怎么用?C# ManualResetEvent.Set使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Threading.ManualResetEvent
的用法示例。
在下文中一共展示了ManualResetEvent.Set方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ThreadGlobalTimeServerIsShared
public void ThreadGlobalTimeServerIsShared()
{
var ts1 = new TestDateTimeServer(now: new DateTime(2011, 1, 1));
var ts2 = new TestDateTimeServer(now: new DateTime(2012, 1, 1));
var g1 = new ManualResetEvent(false);
var g2 = new ManualResetEvent(false);
DateTime? t1Date = null;
var t1 = new Thread(() => {
DateTimeServer.SetGlobal(ts1);
g1.WaitOne();
t1Date = DateTimeServer.Now;
g2.Set();
});
var t2 = new Thread(() => {
DateTimeServer.SetGlobal(ts2);
g2.Set();
g1.WaitOne();
});
t1.Start();
t2.Start();
Assert.That(g2.WaitOne(20), Is.True);
g2.Reset();
g1.Set();
Assert.That(g2.WaitOne(20), Is.True);
Assert.That(t1Date, Is.Not.Null);
Assert.That(t1Date, Is.EqualTo(ts2.Now));
}
示例2: MarkForDeletion
/// <summary>
/// Marks message as deleted.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception>
/// <exception cref="POP3_ClientException">Is raised when POP3 serveer returns error.</exception>
public void MarkForDeletion()
{
if(this.IsDisposed){
throw new ObjectDisposedException(this.GetType().Name);
}
if(this.IsMarkedForDeletion){
return;
}
using(MarkForDeletionAsyncOP op = new MarkForDeletionAsyncOP()){
using(ManualResetEvent wait = new ManualResetEvent(false)){
op.CompletedAsync += delegate(object s1,EventArgs<MarkForDeletionAsyncOP> e1){
wait.Set();
};
if(!this.MarkForDeletionAsync(op)){
wait.Set();
}
wait.WaitOne();
wait.Close();
if(op.Error != null){
throw op.Error;
}
}
}
}
示例3: WebBrowser
public WebBrowser(Arguments args)
: this()
{
var address = args["address"].Value as string;
DispatcherThread.StartNew(() =>
{
//TODO: Add ability to define browser settings.
if (address != null)
m_webBrowser = new ChromiumWebBrowser(address);
else
m_webBrowser = new ChromiumWebBrowser("");
}).Wait();
//Ensure that the web browser is initialized.
using (var evt = new ManualResetEvent(false))
{
m_webBrowser.BrowserInitialized += (o, e) => evt.Set();
DispatcherThread.StartNew(() =>
{
if (m_webBrowser.IsBrowserInitialized)
{
evt.Set();
}
});
evt.WaitOne();
}
}
示例4: ExecuteSync
public static void ExecuteSync(string key, string command, Action<Action<object>, Action<Exception, object>> action)
{
var resetEvent = new ManualResetEvent(initialState: false);
Exception exception = null;
action(
//delegate to invoke on success
s => resetEvent.Set(),
//delegate to invoke on test error
(e, s) =>
{
exception = e;
resetEvent.Set();
});
var timeout = KetchupConfig.Current.SyncCommandTimeout;
if (!resetEvent.WaitOne(timeout * 1000))
throw new TimeoutException(
string.Format(
"Command timed out on before async response was returned.\nCommand: {0}\nKey: {1}",
command,
key
));
if (exception != null)
throw exception;
}
示例5: CloseTest
public void CloseTest()
{
int shutdownCount = 0;
int closeCount = 0;
ManualResetEvent resetEvent = new ManualResetEvent(false);
NetworkConnection connection = new NetworkConnection(_client);
connection.Shutdown += (sender, args) =>
{
shutdownCount++;
resetEvent.Set();
};
connection.ConnectionClosed += (sender, args) =>
{
closeCount++;
resetEvent.Set();
};
connection.Start();
connection.Close();
Assert.That(resetEvent.WaitOne(2000));
Assert.That(shutdownCount, Is.EqualTo(0));
Assert.That(closeCount, Is.EqualTo(1));
}
示例6: AcceptAsyncShouldUseAcceptSocketFromEventArgs
public void AcceptAsyncShouldUseAcceptSocketFromEventArgs()
{
var readyEvent = new ManualResetEvent(false);
var mainEvent = new ManualResetEvent(false);
var listenSocket = new Socket(
AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
var serverSocket = new Socket(
AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Socket acceptedSocket = null;
Exception ex = null;
ThreadPool.QueueUserWorkItem(_ =>
{
SocketAsyncEventArgs asyncEventArgs;
try {
listenSocket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listenSocket.Listen(1);
asyncEventArgs = new SocketAsyncEventArgs {AcceptSocket = serverSocket};
asyncEventArgs.Completed += (s, e) =>
{
acceptedSocket = e.AcceptSocket;
mainEvent.Set();
};
} catch (Exception e) {
ex = e;
return;
} finally {
readyEvent.Set();
}
try {
if (listenSocket.AcceptAsync(asyncEventArgs))
return;
acceptedSocket = asyncEventArgs.AcceptSocket;
mainEvent.Set();
} catch (Exception e) {
ex = e;
}
});
Assert.IsTrue(readyEvent.WaitOne(1500));
if (ex != null)
throw ex;
var clientSocket = new Socket(
AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
clientSocket.Connect(listenSocket.LocalEndPoint);
clientSocket.NoDelay = true;
Assert.IsTrue(mainEvent.WaitOne(1500));
Assert.AreEqual(serverSocket, acceptedSocket, "x");
mainEvent.Reset();
if (acceptedSocket != null)
acceptedSocket.Close();
listenSocket.Close();
readyEvent.Close();
mainEvent.Close();
}
示例7: NatsClient_PubSub_Queue
public void NatsClient_PubSub_Queue()
{
string recvMsg = null;
int counter = 0;
using (var nats1 = new NatsClient(NatsUrl))
using (var nats2 = new NatsClient(NatsUrl))
using (var waitHandle = new ManualResetEvent(false))
{
nats1.Connect();
nats1.Subscribe("test", new Options("queue"), (msg, source) => {
Console.WriteLine("Received: {0}", msg);
recvMsg = msg;
counter += 1;
waitHandle.Set();
});
nats2.Connect();
nats2.Subscribe("test", new Options("queue"), (msg, source) =>
{
Console.WriteLine("Received: {0}", msg);
recvMsg = msg;
counter += 1;
waitHandle.Set();
});
nats2.Publish("test", "Hello");
waitHandle.WaitOne(1000);
}
Assert.AreEqual("Hello", recvMsg);
Assert.AreEqual(1, counter);
}
示例8: TestPolling
public void TestPolling()
{
var reddit = new RedditClient(() => new HttpClient());
var pollingClient = new RedditPollingClient(reddit, "funny", TimeSpan.FromSeconds(10), ex => { });
var resetEvent = new ManualResetEvent(false);
var subscription = pollingClient.Posts.Subscribe(
x => Debug.WriteLine($"New post: {x.Title}"),
ex =>
{
Debug.WriteLine($"Error while retrieving reddit posts: {ex.Message}");
resetEvent.Set();
},
() =>
{
Debug.WriteLine("Finished retrieving posts");
resetEvent.Set();
});
pollingClient.Start();
resetEvent.WaitOne(60000);
}
示例9: GetConfig_CanLoadConfigsFromMultipleThreads
public void GetConfig_CanLoadConfigsFromMultipleThreads() {
const string configKey = "MyCustomConfig";
var configLoader = new FakeLoader(false, true);
var configRepository = new ConfigRepository(configLoader);
const int maxThreads = 10;
Exception ex = null;
IConfig config = null;
var getConfigCompletedEvent = new ManualResetEvent(false);
for(int i = 0; i < maxThreads; i++) {
int remainingThreads = i;
ThreadPool.QueueUserWorkItem(s => {
try {
config = configRepository.GetConfig(configKey, false);
if(Interlocked.Decrement(ref remainingThreads) == 0) {
getConfigCompletedEvent.Set();
}
} catch(Exception innerEx) {
getConfigCompletedEvent.Set();
ex = innerEx;
throw;
}
});
}
getConfigCompletedEvent.WaitOne();
getConfigCompletedEvent.Close();
Assert.IsNotNull(config);
Assert.IsNull(ex);
}
示例10: IterateErrorHandlingTest
public void IterateErrorHandlingTest()
{
var xs = Enumerable.Range(0, 10).Select(x => Observable.Return(new Data(x)));
int errors = 0;
Func<IObservable<Data>> createOriginSource = () => TpObservableExtensions.Iterate(xs, x =>
{
if (x.Body != 5)
{
Console.WriteLine("Handler: " + x.Body);
}
else
{
throw new ApplicationException();
}
}, Scheduler.ThreadPool, s => Console.WriteLine("Trace: " + s));
var ev = new ManualResetEvent(false);
var source = TpObservableExtensions.ToSelfRepairingHotObservable(createOriginSource, _ => { }, e =>
{
Console.WriteLine(e);
errors++;
if (errors == 5)
{
ev.Set();
}
});
using (source.Subscribe(x => Console.WriteLine("Observer: " + x.Body), Console.WriteLine, () =>
{
ev.Set();
Console.WriteLine("Observer: completed");
}))
{
ev.WaitOne(TimeSpan.FromSeconds(5)).Should(Be.True);
}
}
示例11: Loaders_are_thread_safe
public void Loaders_are_thread_safe()
{
kernel.Register(Component.For<SlowLoader>());
var @event = new ManualResetEvent(false);
int[] count = {10};
Exception exception = null;
for (int i = 0; i < count[0]; i++)
{
ThreadPool.QueueUserWorkItem(o =>
{
try
{
kernel.Resolve<Implementation>("not registered");
if (Interlocked.Decrement(ref count[0]) == 0)
{
@event.Set();
}
}
catch (Exception e)
{
exception = e;
// this is required because NUnit does not consider it a failure when
// an exception is thrown on a non-main thread and therfore it waits.
@event.Set();
}
}
);
}
@event.WaitOne();
Assert.IsNull(exception);
Assert.AreEqual(0, count[0]);
}
示例12: GetTokens
/// <summary>
/// Get the OAuth tokens required to access the cloud based API (Synchronous)
/// </summary>
/// <param name="code">The code received after the user has given the application permission to access their company files</param>
/// <returns>The tokens that are required to access the user's company files</returns>
public OAuthTokens GetTokens(string code)
{
var wait = new ManualResetEvent(false);
OAuthTokens oauthTokens = null;
Exception ex = null;
var requestUri = default(Uri);
GetTokens(code,
(statusCode, tokens) =>
{
oauthTokens = tokens;
wait.Set();
},
(uri, exception) =>
{
requestUri = uri;
ex = exception;
wait.Set();
});
if (wait.WaitOne(new TimeSpan(0, 0, 0, 60)))
{
ex.ProcessException(requestUri);
}
return oauthTokens;
}
示例13: DownloadData
/// <summary>
/// Downloads the resource as a string from the URI specified.
/// </summary>
/// <param name="address">The URI represented by the Uri object, from which to download data.</param>
/// <returns></returns>
public string DownloadData(Uri address)
{
var initRequest = (HttpWebRequest)WebRequest.Create(address);
var result = String.Empty;
var responseComplete = new ManualResetEvent(false);
if (Headers != null) initRequest.Headers = Headers;
initRequest.BeginGetResponse(ar =>
{
var signaled = false;
try
{
var response = GetResponse(ar);
result = ReadResponseToString(response);
responseComplete.Set();
signaled = true;
}
catch (Exception)
{
if (!signaled)
{
responseComplete.Set();
}
}
}, initRequest);
return result;
}
示例14: SimpleCommunication
public void SimpleCommunication()
{
var reset1 = new ManualResetEvent(false);
var reset2 = new ManualResetEvent(false);
INatterConnection connection2 = null;
var connection1 =_client1.OnConnected(c => reset1.Set()).OnData((c, f) => HandleResponse(f, c)).Call(GetClient2Address());
_client2.OnConnected(c => reset2.Set()).OnData((c, f) => { HandleResponse(f, c); connection2 = c; });
Assert.IsTrue(reset1.WaitOne(TimeSpan.FromSeconds(5)), "Failed to connect");
Assert.IsTrue(reset2.WaitOne(TimeSpan.FromSeconds(5)), "Failed to connect");
reset1.Reset();
reset2.Reset();
_client1.OnDisconnected(c => reset1.Set());
_client2.OnDisconnected(c => reset2.Set());
Send(connection1, StartNumber);
Assert.IsTrue(reset1.WaitOne(TimeSpan.FromSeconds(80)), "Failed to disconnect");
Assert.IsTrue(reset2.WaitOne(TimeSpan.FromSeconds(80)), "Failed to disconnect");
Assert.AreEqual(ConnectionState.Disconnected, connection1.State, "Client not disconnected");
Assert.AreEqual(ConnectionState.Disconnected, connection2.State, "Client not disconnected");
Assert.AreEqual(EndNumber, _lastResult, "Invalid last number");
Assert.AreEqual((EndNumber - StartNumber) + 1, _count, "Invalid count");
}
示例15: ExecuteActionAndWait
/// <summary>
/// Executes a specified method and waits until the action is completed
/// </summary>
/// <param name="action">The action.</param>
public static void ExecuteActionAndWait(Action<IAsyncContinuation> action)
{
var waitHandle = new ManualResetEvent(false);
Exception exception = null;
var continuation = AsyncHelpers.CreateContinuation(
() => waitHandle.Set(),
exc =>
{
exception = exc;
waitHandle.Set();
});
// try it synchronously, otherwise wait
action(continuation);
bool signalOccurred = WaitHandle.WaitAll(new WaitHandle[] { waitHandle }, MaxMillisecondsTimeout);
if (!signalOccurred)
{
throw new TimeoutException(string.Format(CultureInfo.InvariantCulture, "The action has not completed within {0} milliseconds", MaxMillisecondsTimeout));
}
if (exception != null)
{
// wrap the exception to preserve the original call-stack
throw new TaupoInfrastructureException("An exception occurred during asynchronous execution", exception);
}
}