本文整理汇总了C#中System.Threading.ManualResetEvent.Reset方法的典型用法代码示例。如果您正苦于以下问题:C# ManualResetEvent.Reset方法的具体用法?C# ManualResetEvent.Reset怎么用?C# ManualResetEvent.Reset使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Threading.ManualResetEvent
的用法示例。
在下文中一共展示了ManualResetEvent.Reset方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CallbackInvokedMultipleTimes
public void CallbackInvokedMultipleTimes()
{
var reRegisterForFinalize = true;
var callbackInvoked = new ManualResetEvent(false);
GcNotification.Register(state =>
{
callbackInvoked.Set();
return reRegisterForFinalize;
}, null);
GcCollectAndWait();
Assert.True(callbackInvoked.WaitOne(0));
callbackInvoked.Reset();
reRegisterForFinalize = false;
GcCollectAndWait();
Assert.True(callbackInvoked.WaitOne(0));
callbackInvoked.Reset();
// No callback expected the 3rd time
GcCollectAndWait();
Assert.False(callbackInvoked.WaitOne(0));
}
示例2: CallbackInvokedMultipleTimes
public void CallbackInvokedMultipleTimes()
{
int callbackCount = 0;
var callbackInvoked = new ManualResetEvent(false);
GcNotification.Register(state =>
{
callbackCount++;
callbackInvoked.Set();
if (callbackCount < 2)
{
return true;
}
return false;
}, null);
GC.Collect(2, GCCollectionMode.Forced, blocking: true);
Assert.True(callbackInvoked.WaitOne(100));
Assert.Equal(1, callbackCount);
callbackInvoked.Reset();
GC.Collect(2, GCCollectionMode.Forced, blocking: true);
Assert.True(callbackInvoked.WaitOne(100));
Assert.Equal(2, callbackCount);
callbackInvoked.Reset();
// No callback expected the 3rd time
GC.Collect(2, GCCollectionMode.Forced, blocking: true);
Assert.False(callbackInvoked.WaitOne(100));
Assert.Equal(2, callbackCount);
}
示例3: Run
public static void Run()
{
// ExStart:SupportIMAPIdleCommand
// Connect and log in to IMAP
ImapClient client = new ImapClient("imap.domain.com", "username", "password");
ManualResetEvent manualResetEvent = new ManualResetEvent(false);
ImapMonitoringEventArgs eventArgs = null;
client.StartMonitoring(delegate(object sender, ImapMonitoringEventArgs e)
{
eventArgs = e;
manualResetEvent.Set();
});
Thread.Sleep(2000);
SmtpClient smtpClient = new SmtpClient("exchange.aspose.com", "username", "password");
smtpClient.Send(new MailMessage("[email protected]", "[email protected]", "EMAILNET-34875 - " + Guid.NewGuid(), "EMAILNET-34875 Support for IMAP idle command"));
manualResetEvent.WaitOne(10000);
manualResetEvent.Reset();
Console.WriteLine(eventArgs.NewMessages.Length);
Console.WriteLine(eventArgs.DeletedMessages.Length);
client.StopMonitoring("Inbox");
smtpClient.Send(new MailMessage("[email protected]", "[email protected]", "EMAILNET-34875 - " + Guid.NewGuid(), "EMAILNET-34875 Support for IMAP idle command"));
manualResetEvent.WaitOne(5000);
// ExEnd:SupportIMAPIdleCommand
}
示例4: TestAsyncGetTicket
public void TestAsyncGetTicket()
{
BoxManager manager = new BoxManager(ApplicationKey, ServiceUrl, null);
const int someValue = 78435;
ManualResetEvent wait = new ManualResetEvent(false);
bool callbackWasExecuted = false;
OperationFinished<GetTicketResponse> response = resp =>
{
Assert.IsNull(resp.Error);
Assert.IsNotNull(resp.Ticket);
Assert.IsInstanceOfType(typeof(int), resp.UserState);
Assert.AreEqual(GetTicketStatus.Successful, resp.Status);
int userStatus = (int) resp.UserState;
Assert.AreEqual(someValue, userStatus);
callbackWasExecuted = true;
wait.Reset();
};
manager.GetTicket(response, someValue);
wait.WaitOne(30000);
Assert.IsTrue(callbackWasExecuted, "Callback was not executed. The operation has timed out");
}
示例5: Test
public static void Test(ITransport t, IQueueStrategy strategy,
Endpoint queueEndpoint, Action<Message> send, Func<MessageEnumerator>
enumer)
{
Guid id = Guid.NewGuid();
var serializer = new XmlMessageSerializer(new
DefaultReflection(), new DefaultKernel());
var subscriptionStorage = new MsmqSubscriptionStorage(new
DefaultReflection(),
serializer,
queueEndpoint.Uri,
new
EndpointRouter(),
strategy);
subscriptionStorage.Initialize();
var wait = new ManualResetEvent(false);
subscriptionStorage.SubscriptionChanged += () => wait.Set();
t.AdministrativeMessageArrived +=
subscriptionStorage.HandleAdministrativeMessage;
Message msg = new MessageBuilder
(serializer).GenerateMsmqMessageFromMessageBatch(new
AddInstanceSubscription
{
Endpoint = queueEndpoint.Uri.ToString(),
InstanceSubscriptionKey = id,
Type = typeof (TestMessage2).FullName,
});
send(msg);
wait.WaitOne();
msg = new MessageBuilder
(serializer).GenerateMsmqMessageFromMessageBatch(new
RemoveInstanceSubscription
{
Endpoint = queueEndpoint.Uri.ToString(),
InstanceSubscriptionKey = id,
Type = typeof (TestMessage2).FullName,
});
wait.Reset();
send(msg);
wait.WaitOne();
IEnumerable<Uri> uris = subscriptionStorage
.GetSubscriptionsFor(typeof (TestMessage2));
Assert.Equal(0, uris.Count());
int count = 0;
MessageEnumerator copy = enumer();
while (copy.MoveNext()) count++;
Assert.Equal(0, count);
}
示例6: TestSuccesfulConnection
public void TestSuccesfulConnection()
{
// setup
Uri url = new Uri("http://test.com");
CancellationTokenSource cts = new CancellationTokenSource();
List<EventSourceState> states = new List<EventSourceState>();
ServiceResponseMock response = new ServiceResponseMock(url, System.Net.HttpStatusCode.OK);
WebRequesterFactoryMock factory = new WebRequesterFactoryMock(response);
ManualResetEvent stateIsOpen = new ManualResetEvent(false);
TestableEventSource es = new TestableEventSource(url, factory);
es.StateChanged += (o, e) =>
{
states.Add(e.State);
if (e.State == EventSourceState.OPEN)
{
stateIsOpen.Set();
cts.Cancel();
}
};
// act
stateIsOpen.Reset();
es.Start(cts.Token);
stateIsOpen.WaitOne();
// assert
Assert.IsTrue(states.Count == 2);
Assert.AreEqual(states[0], EventSourceState.CONNECTING);
Assert.AreEqual(states[1], EventSourceState.OPEN);
}
示例7: StartListening
public static void StartListening(int port = 11001)
{
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = IPAddress.Parse(LocalSettings.ServerIP);
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port);
_allDone = new ManualResetEvent(false);
// Create a TCP/IP socket.
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and listen for incoming connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(100);
while (true)
{
// Set the event to nonsignaled state.
_allDone.Reset();
// Start an asynchronous socket to listen for connections.
listener.BeginAccept(
AcceptCallback,
listener);
// Wait until a connection is made before continuing.
_allDone.WaitOne();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
示例8: FilteringTargetWrapperAsyncTest2
public void FilteringTargetWrapperAsyncTest2()
{
var myMockCondition = new MyMockCondition(false);
var myTarget = new MyAsyncTarget();
var wrapper = new FilteringTargetWrapper(myTarget, myMockCondition);
wrapper.Initialize(CommonCfg);
var logEvent = new LogEventInfo();
Exception lastException = null;
var continuationHit = new ManualResetEvent(false);
Action<Exception> continuation =
ex =>
{
lastException = ex;
continuationHit.Set();
};
wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
continuationHit.WaitOne();
Assert.IsNull(lastException);
Assert.AreEqual(0, myTarget.WriteCount);
Assert.AreEqual(1, myMockCondition.CallCount);
continuationHit.Reset();
wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
continuationHit.WaitOne();
Assert.IsNull(lastException);
Assert.AreEqual(0, myTarget.WriteCount);
Assert.AreEqual(2, myMockCondition.CallCount);
}
示例9: Start
/// <summary>
/// Start server and begin accepting clients
/// </summary>
public static void Start()
{
futureMoves = new Queue<FutureMove>();
clientsPlaying = new List<Connection>();
clientUpdate = new List<Connection>();
clientAI = new List<Connection>();
clientPlayers = new List<Connection>();
clientsAll = new List<Connection>();
updateTimer.Elapsed += new ElapsedEventHandler(UpdateTick);
updateTimer.AutoReset = false;
if (listener != null) listener.Stop();
listener = TcpListener.Create(Program.port);
listener.Start();
allDone = new ManualResetEvent(false);
try
{
while (true)
{
allDone.Reset();
listener.BeginAcceptTcpClient(new AsyncCallback(AcceptTcpClient), listener);
allDone.WaitOne();
}
}
catch (ThreadAbortException)
{
listener.Stop();
}
}
示例10: TestAsyncGetAccountInfo_WhenUserIsNotLoggedIn_ThenStatusIsNotLoggedIn
public void TestAsyncGetAccountInfo_WhenUserIsNotLoggedIn_ThenStatusIsNotLoggedIn()
{
const int status = 847587532;
ManualResetEvent wait = new ManualResetEvent(false);
bool callbackWasExecuted = false;
OperationFinished<GetAccountInfoResponse> callback = resp =>
{
Assert.AreEqual(GetAccountInfoStatus.NotLoggedIn, resp.Status);
Assert.IsInstanceOf(typeof(int), resp.UserState);
Assert.AreEqual(status, (int)resp.UserState);
Assert.IsNull(resp.Error);
Assert.IsNull(resp.User);
callbackWasExecuted = true;
wait.Reset();
};
Context.Manager.Logout();
Context.Manager.GetAccountInfo(callback, status);
wait.WaitOne(30000);
Assert.IsTrue(callbackWasExecuted, "Callback was not executed. The operation has timed out");
}
示例11: TestAsyncGetAccountInfo
public void TestAsyncGetAccountInfo()
{
const int status = 847587532;
ManualResetEvent wait = new ManualResetEvent(false);
bool callbackWasExecuted = false;
OperationFinished<GetAccountInfoResponse> callback = resp =>
{
Assert.AreEqual(GetAccountInfoStatus.Successful, resp.Status);
Assert.IsNull(resp.Error);
Assert.IsInstanceOf(typeof(int), resp.UserState);
Assert.AreEqual(status, (int)resp.UserState);
Assert.IsNotNull(resp.User);
Assert.AreEqual(Context.AuthenticatedUser.AccessID, resp.User.AccessID);
Assert.AreEqual(Context.AuthenticatedUser.ID, resp.User.ID);
Assert.AreEqual(Context.AuthenticatedUser.MaxUploadSize, resp.User.MaxUploadSize);
Assert.AreEqual(Context.AuthenticatedUser.SpaceAmount, resp.User.SpaceAmount);
Assert.AreEqual(Context.AuthenticatedUser.SpaceUsed, resp.User.SpaceUsed);
StringAssert.IsMatch(Context.AuthenticatedUser.Email, resp.User.Email);
StringAssert.IsMatch(Context.AuthenticatedUser.Login, resp.User.Login);
callbackWasExecuted = true;
wait.Reset();
};
Context.Manager.GetAccountInfo(callback, status);
wait.WaitOne(30000);
Assert.IsTrue(callbackWasExecuted, "Callback was not executed. The operation has timed out");
}
示例12: ContentLoader
public ContentLoader(ContentLoaderProgressHandler progress)
{
LoaderQueue = new Queue<ContentLoaderItem>();
ContinueLoaderThreadEvent = new ManualResetEvent(false);
ContentLoaderThread = new Thread(delegate() {
double itemIndex = 0;
while (ContentLoaderThread.ThreadState != ThreadState.Aborted)
{
if (LoaderQueue.Count > 0)
{
ContentLoaderItem item = LoaderQueue.Dequeue();
progress((++itemIndex) / (itemIndex + LoaderQueue.Count), item.Description);
item.Handler(item.Target);
}
else
{
ContinueLoaderThreadEvent.WaitOne();
}
ContinueLoaderThreadEvent.Reset();
}
});
ContentLoaderThread.Start();
}
示例13: MockPresenter
public MockPresenter(Page.ePageType activePageType = Page.ePageType.AVItemCollectionGallery,
string excludedTitles = "Popular,TV,V,W,Sports,ESPN,News",
int imageWidth = IMAGE_WIDTH, int imageHeight = IMAGE_HEIGHT)
{
// start logging during mocking
SetupLogging();
_model = MediaServerModel.GetInstance();
TitlesExcludedFromImageReplacement = excludedTitles;
ImageWidth = imageWidth;
ImageHeight = imageHeight;
AVItemCollections = new ObservableCollection<UPnPCollection>();
AVItems = new ObservableCollection<UPnPItem>();
DetailItem = new ObservableCollection<UPnPItem>();
Items = new ObservableCollection<AVItemBase>();
_allDoneEvent = new ManualResetEvent(false);
Logger.TraceInfo(MethodBase.GetCurrentMethod(), "MockPresenter _model: {0}", _model.Actions.ContentDirectory.Name);
_model.Actions.ContentDirectory.NewDeviceFound += NewDeviceFound;
_model.Actions.ContentDirectory.OnCreateControlPoint(null);
_allDoneEvent.WaitOne();
_allDoneEvent.Reset();
WaitTimeBetweenGetImageInMilliseconds = 0;
StartBackgroundThreadToGetImages();
PropertyChanged += OnLocalPropertyChanged;
// default to the showing a collection
ActivePageType = activePageType;
//ActivePageType = Page.ePageType.AVItemGallery;
//ActivePageType = Page.ePageType.AVItemDetails;
_allDoneEvent.WaitOne(TimeSpan.FromSeconds(15D));
}
示例14: Main2
public static void Main2(string[] args)
{
ManualResetEvent conn = new ManualResetEvent(false);
int count = 0;
Socket main = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint bindingPoint = new IPEndPoint(IPAddress.Any,6199);
main.Bind(bindingPoint);
main.Listen(10);
Console.WriteLine("main socket status: Blocking:{0}, localIP:{1}", main.Blocking, main.LocalEndPoint.ToString());
do
{
conn.Reset();
lock (main)
{
count++;
}
main.BeginAccept(AceptCallback, new stateObj { sck = main, ClientNo = count, conn = conn });
Console.WriteLine("wait one : " + count);
conn.WaitOne();
}
while (true);
Console.ReadKey();
main.Close(1000);
}
示例15: 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();
}