本文整理汇总了C#中System.Threading.AutoResetEvent.WaitOne方法的典型用法代码示例。如果您正苦于以下问题:C# AutoResetEvent.WaitOne方法的具体用法?C# AutoResetEvent.WaitOne怎么用?C# AutoResetEvent.WaitOne使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Threading.AutoResetEvent
的用法示例。
在下文中一共展示了AutoResetEvent.WaitOne方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: TestDelete
public void TestDelete()
{
FileInfo file = new FileInfo(@"d:\X16-42552VS2010UltimTrial1.txt");
AutoResetEvent are = new AutoResetEvent(false);
string key = null;
HttpCommunicate.Upload(file, (result, warning) =>
{
Console.WriteLine("result:" + result);
key = result + "";
are.Set();
}, error =>
{
Console.WriteLine("error:" + error);
are.Set();
});
are.WaitOne();
are.Reset();
FileDeletePackage package = new FileDeletePackage();
package.key = key;
HttpCommunicate.Request(package, (result, warning) =>
{
Console.WriteLine("file:" + result);
are.Set();
}, error =>
{
Console.WriteLine("error:" + error);
are.Set();
});
are.WaitOne();
}
示例2: CurrentIsVisibleAccrossThreads
public void CurrentIsVisibleAccrossThreads()
{
var sqlCharacters = new TestSqlCharacters();
SqlCharacters actual = null;
var handle = new AutoResetEvent(false);
var thread1 = new Thread(() =>
{
SqlCharacters.Current = sqlCharacters;
handle.Set();
});
var thread2 = new Thread(() =>
{
actual = SqlCharacters.Current;
handle.Set();
});
thread1.Start();
handle.WaitOne();
thread2.Start();
handle.WaitOne();
thread1.Abort();
thread2.Abort();
Assert.Same(sqlCharacters, actual);
}
示例3: ClearMarkedPosts
public static bool ClearMarkedPosts(ThreadMetadata thread, int timeout = CoreConstants.DEFAULT_TIMEOUT_IN_MILLISECONDS)
{
// create request
HttpWebRequest request = AwfulWebRequest.CreateFormDataPostRequest(
"http://forums.somethingawful.com/showthread.php",
"application/x-www-form-urlencoded");
// begin request stream creation and wait...
var signal = new AutoResetEvent(false);
var result = request.BeginGetRequestStream(callback =>
SendClearMarkedPostRequest(callback, signal, thread),
request);
signal.WaitOne();
// begin response stream and wait...
request = result.AsyncState as HttpWebRequest;
result = request.BeginGetResponse(callback => { signal.Set(); }, request);
signal.WaitOne(timeout);
if (!result.IsCompleted)
throw new TimeoutException();
// process the response and return status
bool success = ProcessClearMarkedPostResponse(result);
return success;
}
示例4: Test_SendToWrongPort
public void Test_SendToWrongPort()
{
IPEndPoint ep1 = new IPEndPoint (IPAddress.Parse ("10.0.0.1"), 10000);
IPEndPoint ep2 = new IPEndPoint (IPAddress.Parse ("10.0.0.2"), 10000);
VirtualNetwork network = new VirtualNetwork (LatencyTypes.Constant (20), 5, PacketLossType.Lossless (), 2);
byte[] msg = new byte[]{0, 1, 2, 3};
try {
using (AutoResetEvent done = new AutoResetEvent (false))
using (VirtualDatagramEventSocket sock1 = new VirtualDatagramEventSocket (network, ep1.Address))
using (VirtualDatagramEventSocket sock2 = new VirtualDatagramEventSocket (network, ep2.Address)) {
sock1.Bind (new IPEndPoint (IPAddress.Any, ep1.Port));
sock2.Bind (new IPEndPoint (IPAddress.Any, ep2.Port));
sock1.Received += new DatagramReceiveEventHandler (delegate (object sender, DatagramReceiveEventArgs e) {
done.Set ();
});
sock2.Received += new DatagramReceiveEventHandler (delegate (object sender, DatagramReceiveEventArgs e) {
done.Set ();
});
sock1.SendTo (msg, new IPEndPoint (ep2.Address, ep2.Port + 1));
Assert.IsFalse (done.WaitOne (500));
sock2.SendTo (msg, ep1);
Assert.IsTrue (done.WaitOne ());
}
} finally {
network.Close ();
}
}
示例5: Main
static void Main(string[] args)
{
AutoResetEvent syncEvent = new AutoResetEvent(false);
// create the workflow app and add handlers for the Idle and Completed actions
WorkflowApplication app = new WorkflowApplication(new Sequence1());
app.Idle = delegate(WorkflowApplicationIdleEventArgs e)
{
syncEvent.Set();
};
app.Completed = delegate(WorkflowApplicationCompletedEventArgs e)
{
syncEvent.Set();
};
// start the application
app.Run();
syncEvent.WaitOne();
// read some text from the console and resume the readText bookmark (created in the first WaitForInput activity)
string text = Console.ReadLine();
app.ResumeBookmark("readText", text);
syncEvent.WaitOne();
// read some text from the console, convert it to number, and resume the readNumber bookmark (created in the second WaitForInput activity)
int number = ReadNumberFromConsole();
app.ResumeBookmark("readNumber", number);
syncEvent.WaitOne();
Console.WriteLine("");
Console.WriteLine("Press [ENTER] to exit...");
Console.ReadLine();
}
示例6: Do_Timeout
public void Do_Timeout()
{
var sw = Stopwatch.StartNew();
const int ms = 100;
var i = 0;
var ellapsed = 0L;
var wait = new AutoResetEvent(false);
Do.Timeout(() =>
{
ellapsed = sw.ElapsedMilliseconds;
i++;
wait.Set();
}, ms);
if (wait.WaitOne(ms * 3))
{
Assert.AreEqual(1, i);
Assert.IsTrue(ellapsed > ms * .9);
} else
{
Assert.Fail("callback not executed.");
}
sw.Restart();
var killswitch = Do.Timeout(() => { wait.Set(); }, ms * 2);
killswitch.Kill();
ellapsed = sw.ElapsedMilliseconds;
Assert.IsTrue(ellapsed < ms * 2);
if (wait.WaitOne(ms * 4))
{
Assert.Fail("Unable to stop timeout.");
}
}
示例7: Main
static void Main(string[] args)
{
// Create an event to signal the timeout count threshold in the timer callback.
AutoResetEvent autoEvent = new AutoResetEvent(false);
StatusChecker statusChecker = new StatusChecker(10);
// Create an inferred delegate that invokes methods for the timer.
TimerCallback tcb = statusChecker.CheckStatus;
// Create a timer that signals the delegate to invoke CheckStatus after one second,
// and every 1/4 second thereafter.
Console.WriteLine("{0} Creating timer.\n", DateTime.Now.ToString("h:mm:ss.fff"));
Timer stateTimer = new Timer(tcb, autoEvent, 1000, 250);
// When autoEvent signals, change the period to every 1/2 second.
autoEvent.WaitOne(5000, false);
stateTimer.Change(0, 500);
Console.WriteLine("\nChanging period.\n");
// When autoEvent signals the second time, dispose of the timer.
autoEvent.WaitOne(5000, false);
stateTimer.Dispose();
Console.WriteLine("\nDestroying timer.");
}
示例8: CreateClient
/// <summary>
/// Create a Pusher Client, and subscribes a user
/// </summary>
/// <param name="pusherServer">Server to connect to</param>
/// <param name="reset">The AutoReset to control the subscription by the client</param>
/// <param name="channelName">The name of the channel to subscribe to</param>
/// <returns>A subscribed client</returns>
public static PusherClient.Pusher CreateClient(Pusher pusherServer, AutoResetEvent reset, string channelName)
{
PusherClient.Pusher pusherClient =
new PusherClient.Pusher(Config.AppKey, new PusherClient.PusherOptions()
{
Authorizer = new InMemoryAuthorizer(
pusherServer,
new PresenceChannelData()
{
user_id = "Mr Pusher",
user_info = new { twitter_id = "@pusher" }
})
});
pusherClient.Connected += delegate { reset.Set(); };
pusherClient.Connect();
reset.WaitOne(TimeSpan.FromSeconds(5));
var channel = pusherClient.Subscribe(channelName);
channel.Subscribed += delegate { reset.Set(); };
reset.WaitOne(TimeSpan.FromSeconds(5));
return pusherClient;
}
示例9: Success
public void Success()
{
AutoResetEvent completed = new AutoResetEvent(false);
if (Socket.OSSupportsIPv4)
{
int port, port1;
using (SocketTestServer.SocketTestServerFactory(IPAddress.Loopback, out port))
using (SocketTestServer.SocketTestServerFactory(IPAddress.Loopback, out port1))
{
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.Completed += OnCompleted;
args.UserToken = completed;
args.RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, port);
args.DisconnectReuseSocket = true;
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Assert.True(client.ConnectAsync(args));
Assert.True(completed.WaitOne(Configuration.PassingTestTimeout), "Timed out while waiting for connection");
Assert.Equal<SocketError>(SocketError.Success, args.SocketError);
client.Disconnect(true);
args.RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, port1);
Assert.True(client.ConnectAsync(args));
Assert.True(completed.WaitOne(Configuration.PassingTestTimeout), "Timed out while waiting for connection");
Assert.Equal<SocketError>(SocketError.Success, args.SocketError);
client.Dispose();
}
}
}
示例10: DisconnectAsync_Success
public void DisconnectAsync_Success()
{
AutoResetEvent completed = new AutoResetEvent(false);
IPEndPoint loopback = new IPEndPoint(IPAddress.Loopback, 0);
using (var server1 = SocketTestServer.SocketTestServerFactory(SocketImplementationType.Async, loopback))
using (var server2 = SocketTestServer.SocketTestServerFactory(SocketImplementationType.Async, loopback))
{
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.Completed += OnCompleted;
args.UserToken = completed;
args.RemoteEndPoint = server1.EndPoint;
args.DisconnectReuseSocket = true;
using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
Assert.True(client.ConnectAsync(args));
completed.WaitOne();
Assert.Equal(SocketError.Success, args.SocketError);
Assert.True(client.DisconnectAsync(args));
completed.WaitOne();
Assert.Equal(SocketError.Success, args.SocketError);
args.RemoteEndPoint = server2.EndPoint;
Assert.True(client.ConnectAsync(args));
completed.WaitOne();
Assert.Equal(SocketError.Success, args.SocketError);
}
}
}
示例11: describe_custom_gossip_message_factory_creating_different_message_types
public void describe_custom_gossip_message_factory_creating_different_message_types()
{
var clusterConfig = new GossipClusterConfig { ClusterKey = Encoding.UTF8.GetBytes("ClusterKey") };
var nodeConfig1 = new GossipNodeConfig(new IPEndPoint(IPAddress.Loopback, NodePort1));
var nodeConfig2 = new GossipNodeConfig(new IPEndPoint(IPAddress.Loopback, NodePort2));
var message1 = new GossipMessage1();
var message2 = new GossipMessage2();
GossipMessageFactory.CreateMessage += CreateMessage;
using (var node1 = new GossipNode(nodeConfig1, clusterConfig))
using (var node2 = new GossipNode(nodeConfig2, clusterConfig))
{
var received = new AutoResetEvent(false);
GossipMessage receivedMsg = null;
node1.OnMessageReceived += (node, conn, msg) =>
{
receivedMsg = msg;
received.Set();
};
node1.StartListening();
node2.StartListening();
node1.Cluster.Join(new GossipClusterMember(nodeConfig1.NodeId, nodeConfig2, node2.Authenticator));
node2.Cluster.Join(new GossipClusterMember(nodeConfig2.NodeId, nodeConfig1, node1.Authenticator));
node2.Cluster.BroadcastMessage(message1);
if (!received.WaitOne(Timeout)) Assert.Fail();
Assert.IsInstanceOf<GossipMessage1>(receivedMsg);
node2.Cluster.BroadcastMessage(message2);
if (!received.WaitOne(Timeout)) Assert.Fail();
Assert.IsInstanceOf<GossipMessage2>(receivedMsg);
}
}
示例12: Should_Receive_Many_Envelopes_When_Filter_Returns_True
public void Should_Receive_Many_Envelopes_When_Filter_Returns_True()
{
InMemoryEnvelopeBus bus = new InMemoryEnvelopeBus();
AutoResetEvent waitHandle = new AutoResetEvent(false);
Envelope env = new Envelope();
env.Payload = Encoding.UTF8.GetBytes("Test");
Mock<IRegistration> reg = _mocker.Create<IRegistration>();
reg.Setup(r => r.Filter).Returns(new Predicate<Envelope>(e => true));
reg.Setup(r => r.Handle(env)).Callback(() => waitHandle.Set());
bus.Register(reg.Object);
bus.Send(env);
waitHandle.WaitOne(5000);
bus.Send(env);
waitHandle.WaitOne(5000);
bus.Send(env);
waitHandle.WaitOne(5000);
bus.Send(env);
waitHandle.WaitOne(5000);
bus.Send(env);
waitHandle.WaitOne(5000);
reg.Verify(r => r.Handle(env), Times.Exactly(5));
}
示例13: MessageAfterExceptionTest
public void MessageAfterExceptionTest()
{
Exception e = null;
AutoResetEvent even = new AutoResetEvent(false);
int y = 0;
var a = new Arbitr<Message, NOPMessage>(
(z) =>
{
y = 1 / z.x;
even.Set();
},
(z) =>
{
e = z;
even.Set();
});
a.Send(new Message() { x = 0 });
bool completed = even.WaitOne(500);
Assert.IsTrue(completed);
Assert.IsNotNull(e);
Assert.AreEqual(y, 0);
e = null;
a.Send(new Message() { x = 1 });
completed = even.WaitOne(500);
Assert.IsTrue(completed);
Assert.IsNull(e);
Assert.AreEqual(y, 1);
}
示例14: AsyncStorageModule_InvalidKeyValue_Method
public void AsyncStorageModule_InvalidKeyValue_Method()
{
var module = new AsyncStorageModule();
var waitHandle = new AutoResetEvent(false);
var error = default(JObject);
var result = default(JArray);
var callback = new MockCallback(res =>
{
error = res.Length > 0 ? (JObject)res[0] : null;
result = res.Length > 1 ? (JArray)res[1] : null;
waitHandle.Set();
});
var array = new[]
{
new[] { "5", "5", "5" },
};
module.clear(callback);
Assert.IsTrue(waitHandle.WaitOne());
Assert.IsNull(error);
Assert.IsNull(result);
module.multiSet(array, callback);
Assert.IsTrue(waitHandle.WaitOne());
Assert.AreEqual(error["message"], "Invalid Value");
Assert.IsNull(result);
}
示例15: when_receiving_message_then_can_send_new_message
public void when_receiving_message_then_can_send_new_message()
{
var secondReceiver = new TestableMessageReceiver(this.connectionFactory);
this.sender.Send(new Message("message1"));
var waitEvent = new AutoResetEvent(false);
string receiver1Message = null;
string receiver2Message = null;
this.receiver.MessageReceived += (s, e) =>
{
waitEvent.Set();
receiver1Message = e.Message.Body;
waitEvent.WaitOne();
};
secondReceiver.MessageReceived += (s, e) =>
{
receiver2Message = e.Message.Body;
};
ThreadPool.QueueUserWorkItem(_ => { this.receiver.ReceiveMessage(); });
Assert.IsTrue(waitEvent.WaitOne(TimeSpan.FromSeconds(10)));
this.sender.Send(new Message("message2"));
secondReceiver.ReceiveMessage();
waitEvent.Set();
Assert.IsTrue("message1" == receiver1Message);
Assert.IsTrue("message2" == receiver2Message);
}