本文整理汇总了C#中System.Threading.ManualResetEvent类的典型用法代码示例。如果您正苦于以下问题:C# ManualResetEvent类的具体用法?C# ManualResetEvent怎么用?C# ManualResetEvent使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ManualResetEvent类属于System.Threading命名空间,在下文中一共展示了ManualResetEvent类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GenerateFirstCrossWord
static ICrossBoard GenerateFirstCrossWord(ICrossBoard board, ICrossDictionary dictionary, string puzzle)
{
var placer = new PuzzlePlacer(board, puzzle);
var cts = new CancellationTokenSource();
var mre = new ManualResetEvent(false);
ICrossBoard successFullBoard = null;
foreach (var boardWithPuzzle in placer.GetAllPossiblePlacements(dictionary))
{
//boardWithPuzzle.WriteTo(new StreamWriter(Console.OpenStandardOutput(), Console.OutputEncoding) { AutoFlush = true });
var gen = new CrossGenerator(dictionary, boardWithPuzzle);
var t = Task.Factory.StartNew(() =>
{
foreach (var solution in gen.Generate())
{
successFullBoard = solution;
cts.Cancel();
mre.Set();
break; //interested in the first one
}
}, cts.Token);
if (cts.IsCancellationRequested)
break;
}
mre.WaitOne();
return successFullBoard;
}
示例2: Initialize
// Initialize Parallel class's instance creating required number of threads
// and synchronization objects
private void Initialize( )
{
threadsCount = System.Environment.ProcessorCount;
//No point starting new threads for a single core computer
if (threadsCount <= 1) {
return;
}
// array of events, which signal about available job
jobAvailable = new AutoResetEvent[threadsCount];
// array of events, which signal about available thread
threadIdle = new ManualResetEvent[threadsCount];
// array of threads
threads = new Thread[threadsCount];
for ( int i = 0; i < threadsCount; i++ )
{
jobAvailable[i] = new AutoResetEvent( false );
threadIdle[i] = new ManualResetEvent( true );
threads[i] = new Thread( new ParameterizedThreadStart( WorkerThread ) );
threads[i].IsBackground = false;
threads[i].Start( i );
}
}
示例3: NetAsyncDownloader
/// <summary>
/// Returns a perfectly boring NetAsyncDownloader.
/// </summary>
public NetAsyncDownloader(IUser user)
{
User = user;
downloads = new List<NetAsyncDownloaderDownloadPart>();
modules = new List<CkanModule>();
complete_or_canceled = new ManualResetEvent(false);
}
示例4: ExpiredLazyTriggerRemovesItemInBackground
public void ExpiredLazyTriggerRemovesItemInBackground()
{
var clock = new TestClock();
var cache = CreateCache(clock);
string key = "myKey";
var obj = new object();
var callbackInvoked = new ManualResetEvent(false);
var trigger = new TestTrigger() { ActiveExpirationCallbacks = false };
cache.Set(key, context =>
{
context.AddExpirationTrigger(trigger);
context.RegisterPostEvictionCallback((subkey, value, reason, state) =>
{
// TODO: Verify params
var localCallbackInvoked = (ManualResetEvent)state;
localCallbackInvoked.Set();
}, state: callbackInvoked);
return obj;
});
var found = cache.TryGetValue(key, out obj);
Assert.True(found);
clock.Add(TimeSpan.FromMinutes(2));
trigger.IsExpired = true;
var ignored = cache.Get("otherKey"); // Background expiration checks are triggered by misc cache activity.
Assert.True(callbackInvoked.WaitOne(100), "Callback");
found = cache.TryGetValue(key, out obj);
Assert.False(found);
}
示例5: AddExpiredTriggerPreventsCaching
public void AddExpiredTriggerPreventsCaching()
{
var cache = CreateCache();
string key = "myKey";
var obj = new object();
var callbackInvoked = new ManualResetEvent(false);
var trigger = new TestTrigger() { IsExpired = true };
var result = cache.Set(key, context =>
{
context.AddExpirationTrigger(trigger);
context.RegisterPostEvictionCallback((subkey, value, reason, state) =>
{
// TODO: Verify params
var localCallbackInvoked = (ManualResetEvent)state;
localCallbackInvoked.Set();
}, state: callbackInvoked);
return obj;
});
Assert.Same(obj, result); // The created item should be returned, but not cached.
Assert.True(trigger.IsExpiredWasCalled);
Assert.False(trigger.ActiveExpirationCallbacksWasCalled);
Assert.Null(trigger.Registration);
Assert.True(callbackInvoked.WaitOne(100), "Callback");
result = cache.Get(key);
Assert.Null(result); // It wasn't cached
}
示例6: UdpListenerAdapter
UdpListenerAdapter()
{
webHostCallbacks = new WebhostListenerCallbacks();
webHostCallbacks.dwBytesInCallbackStructure = Marshal.SizeOf(webHostCallbacks);
webHostCallbacks.applicationAppPoolChanged = new WCB.ApplicationAppPoolChanged(OnApplicationAppPoolChanged);
webHostCallbacks.applicationBindingsChanged = new WCB.ApplicationBindingsChanged(OnApplicationBindingsChanged);
webHostCallbacks.applicationCreated = new WCB.ApplicationCreated(OnApplicationCreated);
webHostCallbacks.applicationDeleted = new WCB.ApplicationDeleted(OnApplicationDeleted);
webHostCallbacks.applicationPoolAllListenerChannelInstancesStopped = new WCB.ApplicationPoolAllListenerChannelInstancesStopped(OnApplicationPoolAllListenerChannelInstancesStopped);
webHostCallbacks.applicationPoolCanOpenNewListenerChannelInstance = new WCB.ApplicationPoolCanOpenNewListenerChannelInstance(OnApplicationPoolCanOpenNewListenerChannelInstance);
webHostCallbacks.applicationPoolCreated = new WCB.ApplicationPoolCreated(OnApplicationPoolCreated);
webHostCallbacks.applicationPoolDeleted = new WCB.ApplicationPoolDeleted(OnApplicationPoolDeleted);
webHostCallbacks.applicationPoolIdentityChanged = new WCB.ApplicationPoolIdentityChanged(OnApplicationPoolIdentityChanged);
webHostCallbacks.applicationPoolStateChanged = new WCB.ApplicationPoolStateChanged(OnApplicationPoolStateChanged);
webHostCallbacks.applicationRequestsBlockedChanged = new WCB.ApplicationRequestsBlockedChanged(OnApplicationRequestsBlockedChanged);
webHostCallbacks.configManagerConnected = new WCB.ConfigManagerConnected(OnConfigManagerConnected);
webHostCallbacks.configManagerDisconnected = new WCB.ConfigManagerDisconnected(OnConfigManagerDisconnected);
webHostCallbacks.configManagerInitializationCompleted = new WCB.ConfigManagerInitializationCompleted(OnConfigManagerInitializationCompleted);
initializedEvent = new ManualResetEvent(false);
appManager = new AppManager();
appQueue = new UriLookupTable<App>();
listenerManager = new UdpListenerManager(new DataReceivedCallback(OnDataReceived));
}
示例7: SendPing
public void SendPing()
{
engine.Add(node);
engine.TimeOut = TimeSpan.FromMilliseconds(75);
ManualResetEvent handle = new ManualResetEvent(false);
engine.MessageLoop.QuerySent += delegate(object o, SendQueryEventArgs e) {
if (!e.TimedOut && e.Query is Ping)
handle.Set();
if (!e.TimedOut || !(e.Query is Ping))
return;
PingResponse response = new PingResponse(node.Id, e.Query.TransactionId);
listener.RaiseMessageReceived(response, e.EndPoint);
};
Assert.AreEqual(NodeState.Unknown, node.State, "#1");
DateTime lastSeen = node.LastSeen;
Assert.IsTrue(handle.WaitOne(1000, false), "#1a");
Node nnnn = node;
node = engine.RoutingTable.FindNode(nnnn.Id);
Assert.IsTrue (lastSeen < node.LastSeen, "#2");
Assert.AreEqual(NodeState.Good, node.State, "#3");
}
示例8: Loaders_are_thread_safe
public void Loaders_are_thread_safe()
{
Container.Register(Component.For<ILazyComponentLoader>().ImplementedBy<SlowLoader>());
var @event = new ManualResetEvent(false);
int[] count = { 10 };
Exception exception = null;
for (var i = 0; i < count[0]; i++)
{
ThreadPool.QueueUserWorkItem(o =>
{
try
{
Container.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]);
}
示例9: Execute
public void Execute(string[] args)
{
Options options = new Options(args);
int threadsCount = options.ThreadsCount > 0
? options.ThreadsCount
: Environment.ProcessorCount;
_loopsPerThread = options.MegaLoops * 1000000L;
if (threadsCount == 1)
{
Burn();
}
else
{
_loopsPerThread /= threadsCount;
_gateEvent = new ManualResetEvent(false);
Thread[] threads = new Thread[threadsCount];
for (int i = 0; i < threadsCount; i++)
{
var thread = new Thread(Burn);
thread.IsBackground = true;
thread.Start();
threads[i] = thread;
}
_gateEvent.Set();
foreach (var thread in threads)
thread.Join();
}
}
示例10: ShouldAddNewIncomingPhoneNumberAsynchronously
public void ShouldAddNewIncomingPhoneNumberAsynchronously()
{
manualResetEvent = new ManualResetEvent(false);
var client = new TwilioRestClient(Credentials.TestAccountSid, Credentials.TestAuthToken);
PhoneNumberOptions options = new PhoneNumberOptions();
options.PhoneNumber = "+15005550006";
options.VoiceUrl = "http://example.com/phone";
options.VoiceMethod = "GET";
options.VoiceFallbackUrl = "http://example.com/phone";
options.VoiceFallbackMethod = "GET";
options.SmsUrl = "http://example.com/sms";
options.SmsMethod = "GET";
options.SmsFallbackUrl = "http://example.com/sms";
options.SmsFallbackMethod = "GET";
IncomingPhoneNumber result = null;
client.AddIncomingPhoneNumber(options, number => {
result = number;
manualResetEvent.Set();
});
manualResetEvent.WaitOne();
Assert.IsNotNull(result);
Assert.IsNull(result.RestException);
Assert.IsNotNull(result.Sid);
}
示例11: Wait
public bool Wait(TimeSpan timeout)
{
SpinWait s = new SpinWait();
bool waitResult = true;
while (m_state == 0)
{
if (s.Spin() >= s_spinCount)
{
if (m_eventObj == null)
{
ManualResetEvent newEvent =
new ManualResetEvent(m_state == 1);
if (Interlocked.CompareExchange<EventWaitHandle>(
ref m_eventObj, newEvent, null) == null)
{
// If someone set the flag before seeing the new
// event obj, we must ensure it’s been set.
if (m_state == 1)
m_eventObj.Set();
}
else
{
// Lost the race w/ another thread. Just use
// its event.
newEvent.Close();
}
}
waitResult = m_eventObj.WaitOne(timeout);
}
}
return waitResult;
}
示例12: Capture
// Zero based device index and device params and output window
public Capture(int iDeviceNum, int iWidth, int iHeight, short iBPP, Control hControl)
{
DsDevice[] capDevices;
// Get the collection of video devices
capDevices = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice);
if (iDeviceNum + 1 > capDevices.Length)
{
throw new Exception("No video capture devices found at that index!");
}
try
{
// Set up the capture graph
SetupGraph(capDevices[iDeviceNum], iWidth, iHeight, iBPP, hControl);
// tell the callback to ignore new images
m_PictureReady = new ManualResetEvent(false);
}
catch
{
Dispose();
throw;
}
}
示例13: ShouldAddNewWorkerAsynchronously
public void ShouldAddNewWorkerAsynchronously()
{
RestRequest savedRequest = null;
mockClient.Setup(trc => trc.ExecuteAsync<Worker>(It.IsAny<RestRequest>(), It.IsAny<Action<Worker>>()))
.Callback<RestRequest, Action<Worker>>((request, action) => savedRequest = request);
var client = mockClient.Object;
manualResetEvent = new ManualResetEvent(false);
var friendlyName = Twilio.Api.Tests.Utilities.MakeRandomFriendlyName();
client.AddWorker(WORKSPACE_SID, friendlyName, "WA123", "attributes", worker =>
{
manualResetEvent.Set();
});
manualResetEvent.WaitOne(1);
mockClient.Verify(trc => trc.ExecuteAsync<Worker>(It.IsAny<RestRequest>(), It.IsAny<Action<Worker>>()), Times.Once);
Assert.IsNotNull(savedRequest);
Assert.AreEqual("Workspaces/{WorkspaceSid}/Workers", savedRequest.Resource);
Assert.AreEqual("POST", savedRequest.Method);
Assert.AreEqual(4, savedRequest.Parameters.Count);
var workspaceSidParam = savedRequest.Parameters.Find(x => x.Name == "WorkspaceSid");
Assert.IsNotNull(workspaceSidParam);
Assert.AreEqual(WORKSPACE_SID, workspaceSidParam.Value);
var friendlyNameParam = savedRequest.Parameters.Find(x => x.Name == "FriendlyName");
Assert.IsNotNull(friendlyNameParam);
Assert.AreEqual(friendlyName, friendlyNameParam.Value);
var activitySidParam = savedRequest.Parameters.Find(x => x.Name == "ActivitySid");
Assert.IsNotNull(activitySidParam);
Assert.AreEqual("WA123", activitySidParam.Value);
var attributesParam = savedRequest.Parameters.Find(x => x.Name == "Attributes");
Assert.IsNotNull(attributesParam);
Assert.AreEqual("attributes", attributesParam.Value);
}
示例14: ProcessInfo
private Dictionary<int, ThreadInfo> processThreads; //has relating thread id to its threadInfo object
#endregion Fields
#region Constructors
/// <summary>
/// Constructor for ProcessInfo
/// </summary>
/// <param name="procID">The id of the process</param>
/// <param name="debugger">The debugger</param>
public ProcessInfo(Process process, CorDebugger debug)
{
if (debug == null)
{
throw new ArgumentException("Null Debugger Exception");
}
processThreads = new Dictionary<int, ThreadInfo>();
processCorThreads = new List<CorThread>();
generalThreadInfos = new Dictionary<int, ProcessThread>();
attachedCompletedProcessEvent = new ManualResetEvent(false);
debugger = debug;
processId = process.Id;
generalProcessInfo = Process.GetProcessById(processId);
//CorPublish cp = new CorPublish();
//cpp = cp.GetProcess(processId);
processFullName = process.MainModule.FileName;
processShortName = System.IO.Path.GetFileName(process.MainModule.FileName);
FileVersionInfo fileInfo = FileVersionInfo.GetVersionInfo(processFullName);
description = fileInfo.FileDescription;
company = fileInfo.CompanyName;
//debuggerProcessInfo will be set when the updateInfo function is called
//the reason for this is that the process must be stopped for this to take place
//this happen only when we want it to
}
示例15: 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));
}