本文整理汇总了C#中ManualResetEvent.Reset方法的典型用法代码示例。如果您正苦于以下问题:C# ManualResetEvent.Reset方法的具体用法?C# ManualResetEvent.Reset怎么用?C# ManualResetEvent.Reset使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ManualResetEvent
的用法示例。
在下文中一共展示了ManualResetEvent.Reset方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
public static int Main ()
{
var mre_l = new ManualResetEvent (false);
var mre = new ManualResetEvent (false);
Func<string, Task<string>> f = async l =>
await Task.Factory.StartNew (() => {
if (!mre_l.WaitOne (3000))
throw new ApplicationException ("3");
return l;
});
var r = f ("a");
mre_l.Set ();
if (!r.Wait (3000))
return 1;
if (r.Result != "a")
return 11;
mre_l.Reset ();
Func<Task> ff = async () =>
await Task.Factory.StartNew (() => {
if (!mre_l.WaitOne (3000))
throw new ApplicationException ("3");
});
var rr = ff ();
mre_l.Set ();
if (!rr.Wait (3000))
return 2;
Func<short, Task<short>> f2 = async l => l;
var r2 = f2 (88);
if (r2.Result != 88)
return 3;
mre.Reset ();
mre_l.Reset ();
Action a = async () => await Task.Factory.StartNew (() => {
if (!mre_l.WaitOne (3000))
throw new ApplicationException ("4");
mre.Set ();
}, CancellationToken.None);
a ();
mre_l.Set ();
if (!mre.WaitOne (3000))
return 4;
Console.WriteLine ("ok");
return 0;
}
示例2: TestWaitAny
public void TestWaitAny()
{
int x;
e1 = new ManualResetEvent(false);
e2 = new ManualResetEvent(false);
x = WaitHandle.WaitAny(new WaitHandle[] {e1,e2}, 100,false);
AssertEquals("WaitAny(unset, unset)", x, WaitHandle.WaitTimeout);
e1.Set();
x = WaitHandle.WaitAny(new WaitHandle[] {e1,e2},100, false);
AssertEquals("WaitAny(set, unset)", x, 0);
e1.Reset();
e2.Set();
x = WaitHandle.WaitAny(new WaitHandle[] {e1,e2},100, false);
AssertEquals("WaitAny(set, unset)", x, 1);
e1.Set();
e2.Set();
x = WaitHandle.WaitAny(new WaitHandle[] {e1,e2},100, false);
AssertEquals("WaitAny(set, set)", x, 0);
}
示例3: PingPong
public void PingPong()
{
using (ManualResetEvent mre1 = new ManualResetEvent(true), mre2 = new ManualResetEvent(false))
{
const int Iters = 10;
Task.WaitAll(
Task.Factory.StartNew(() =>
{
for (int i = 0; i < Iters; i++)
{
Assert.True(mre1.WaitOne(FailedWaitTimeout));
mre1.Reset();
mre2.Set();
}
}, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default),
Task.Factory.StartNew(() =>
{
for (int i = 0; i < Iters; i++)
{
Assert.True(mre2.WaitOne(FailedWaitTimeout));
mre2.Reset();
mre1.Set();
}
}, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default));
}
}
示例4: OrderByUpdatedNoFilter
public void OrderByUpdatedNoFilter()
{
var count = 6;
ITrackingCollection<Thing> col = new TrackingCollection<Thing>(
Observable.Never<Thing>(),
OrderedComparer<Thing>.OrderBy(x => x.UpdatedAt).Compare);
col.NewerComparer = OrderedComparer<Thing>.OrderByDescending(x => x.UpdatedAt).Compare;
col.ProcessingDelay = TimeSpan.Zero;
var list1 = new List<Thing>(Enumerable.Range(1, count).Select(i => GetThing(i, i, count - i, "Run 1")).ToList());
var list2 = new List<Thing>(Enumerable.Range(1, count).Select(i => GetThing(i, i, i + count, "Run 2")).ToList());
var evt = new ManualResetEvent(false);
col.Subscribe(t =>
{
if (++count == list1.Count)
evt.Set();
}, () => { });
count = 0;
// add first items
foreach (var l in list1)
col.AddItem(l);
evt.WaitOne();
evt.Reset();
Assert.AreEqual(list1.Count, col.Count);
list1.Sort(new LambdaComparer<Thing>(OrderedComparer<Thing>.OrderByDescending(x => x.CreatedAt).Compare));
CollectionAssert.AreEqual(col, list1);
count = 0;
// replace items
foreach (var l in list2)
col.AddItem(l);
evt.WaitOne();
evt.Reset();
Assert.AreEqual(list2.Count, col.Count);
CollectionAssert.AreEqual(col, list2);
col.Dispose();
}
示例5: WaitOne
public static void WaitOne()
{
ManualResetEvent h = new ManualResetEvent(true);
Assert.True(h.WaitOne());
Assert.True(h.WaitOne(1));
Assert.True(h.WaitOne(TimeSpan.FromMilliseconds(1)));
h.Reset();
Assert.False(h.WaitOne(1));
Assert.False(h.WaitOne(TimeSpan.FromMilliseconds(1)));
}
示例6: SetReset
public void SetReset()
{
using (ManualResetEvent mre = new ManualResetEvent(false))
{
Assert.False(mre.WaitOne(0));
mre.Set();
Assert.True(mre.WaitOne(0));
Assert.True(mre.WaitOne(0));
mre.Set();
Assert.True(mre.WaitOne(0));
mre.Reset();
Assert.False(mre.WaitOne(0));
}
}
示例7: Run
public int Run()
{
ManualResetEvent mre = new ManualResetEvent(true);
if(!mre.WaitOne(0))//,false)) //are.WaitOne returns true if signaled
return -1;
mre.Reset();
if(mre.WaitOne(1000))//,false))
return -3;
mre.Set();
if(mre.WaitOne(0))//,false))
return 100;
Console.WriteLine("ManualResetEvent Broken");
return -3;
}
示例8: FileSystemWatcher_InternalBufferSize_File
public static void FileSystemWatcher_InternalBufferSize_File()
{
using (var file = Utility.CreateTestFile())
using (var watcher = new FileSystemWatcher("."))
{
watcher.Filter = Path.GetFileName(file.Path);
ManualResetEvent unblockHandler = new ManualResetEvent(false);
watcher.Changed += (o, e) =>
{
// block the handling thread
unblockHandler.WaitOne();
};
AutoResetEvent eventOccured = new AutoResetEvent(false);
watcher.Error += (o, e) =>
{
eventOccured.Set();
};
watcher.EnableRaisingEvents = true;
// See note in FileSystemWatcher_Error_File
int originalInternalBufferOperationCapacity = watcher.InternalBufferSize / (16 + 2 * (file.Path.Length + 1));
for (int i = 1; i < originalInternalBufferOperationCapacity * 2; i++)
{
File.SetLastWriteTime(file.Path, DateTime.Now + TimeSpan.FromSeconds(i));
}
unblockHandler.Set();
Utility.ExpectEvent(eventOccured, "error");
// Update InternalBufferSize to accomadate the data
watcher.InternalBufferSize = watcher.InternalBufferSize * 2;
unblockHandler.Reset();
// Send the same number of events.
for (int i = 1; i < originalInternalBufferOperationCapacity * 2; i++)
{
File.SetLastWriteTime(file.Path, DateTime.Now + TimeSpan.FromSeconds(i));
}
unblockHandler.Set();
// This time we should not see an error
Utility.ExpectNoEvent(eventOccured, "error");
}
}
示例9: Run
public int Run()
{
Stopwatch sw = new Stopwatch();
ManualResetEvent mre = new ManualResetEvent(false);
sw.Start();
bool ret = mre.WaitOne(1000);//,false);
sw.Stop();
//We should never get signaled
Console.WriteLine("Expect WaitOne to return False and time-out after 1000 milliseconds waiting for signal.");
Console.WriteLine("Actual return is: " + ret.ToString());
Console.WriteLine("Expect Stopwatch to use entire 1000 milliseconds.");
Console.WriteLine("Actual time taken is: " + sw.ElapsedMilliseconds.ToString());
Console.WriteLine();
if(ret || sw.ElapsedMilliseconds < 900)
return -1;
Console.WriteLine("Manual Reset Event signalled.");
mre.Set();
ret = mre.WaitOne(0);//,false);
Console.WriteLine("Expect WaitOne to return True and time-out after 1000 milliseconds waiting for signal.");
Console.WriteLine("Actual return is: " + ret.ToString());
Console.WriteLine();
if(!ret)
return -3;
mre.Reset();
sw.Reset();
sw.Start();
ret = mre.WaitOne(1000);//,false);
sw.Stop();
//We should never get signaled
Console.WriteLine("Expect WaitOne to return false and time-out after 1000 milliseconds waiting for signal.");
Console.WriteLine("Actual return is: " + ret.ToString());
Console.WriteLine("Expect Stopwatch to use entire 1000 milliseconds.");
Console.WriteLine("Actual time taken is: " + sw.ElapsedMilliseconds.ToString());
if(ret || sw.ElapsedMilliseconds < 900)
return -1;
return 100;
}
示例10: MultipleSortingAndFiltering
public void MultipleSortingAndFiltering()
{
var expectedTotal = 20;
var rnd = new Random(214748364);
var titles1 = Enumerable.Range(1, expectedTotal).Select(x => ((char)('a' + x)).ToString()).ToList();
var dates1 = Enumerable.Range(1, expectedTotal).Select(x => Now + TimeSpan.FromMinutes(x)).ToList();
var idstack1 = new Stack<int>(Enumerable.Range(1, expectedTotal).OrderBy(rnd.Next));
var datestack1 = new Stack<DateTimeOffset>(dates1);
var titlestack1 = new Stack<string>(titles1.OrderBy(_ => rnd.Next()));
var titles2 = Enumerable.Range(1, expectedTotal).Select(x => ((char)('c' + x)).ToString()).ToList();
var dates2 = Enumerable.Range(1, expectedTotal).Select(x => Now + TimeSpan.FromMinutes(x)).ToList();
var idstack2 = new Stack<int>(Enumerable.Range(1, expectedTotal).OrderBy(rnd.Next));
var datestack2 = new Stack<DateTimeOffset>(new List<DateTimeOffset>() {
dates2[2], dates2[0], dates2[1], dates2[3], dates2[5],
dates2[9], dates2[15], dates2[6], dates2[7], dates2[8],
dates2[13], dates2[10], dates2[16], dates2[11], dates2[12],
dates2[14], dates2[17], dates2[18], dates2[19], dates2[4],
});
var titlestack2 = new Stack<string>(titles2.OrderBy(_ => rnd.Next()));
var list1 = Observable.Defer(() => Enumerable.Range(1, expectedTotal)
.OrderBy(rnd.Next)
.Select(x => new Thing(idstack1.Pop(), titlestack1.Pop(), datestack1.Pop()))
.ToObservable())
.Replay()
.RefCount();
var list2 = Observable.Defer(() => Enumerable.Range(1, expectedTotal)
.OrderBy(rnd.Next)
.Select(x => new Thing(idstack2.Pop(), titlestack2.Pop(), datestack2.Pop()))
.ToObservable())
.Replay()
.RefCount();
var col = new TrackingCollection<Thing>(
list1.Concat(list2),
OrderedComparer<Thing>.OrderByDescending(x => x.CreatedAt).Compare,
(item, idx, list) => idx < 5
)
{ ProcessingDelay = TimeSpan.Zero };
var count = 0;
var evt = new ManualResetEvent(false);
col.Subscribe(t =>
{
if (++count == expectedTotal * 2)
evt.Set();
}, () => { });
evt.WaitOne();
evt.Reset();
// it's initially sorted by date, so id list should not match
CollectionAssert.AreNotEqual(list1.Select(x => x.Number).ToEnumerable(), list2.Select(x => x.Number).ToEnumerable());
var sortlist = list1.ToEnumerable().ToArray();
Array.Sort(sortlist, new LambdaComparer<Thing>(OrderedComparer<Thing>.OrderByDescending(x => x.CreatedAt).Compare));
CollectionAssert.AreEqual(sortlist.Take(5), col);
col.SetComparer(OrderedComparer<Thing>.OrderBy(x => x.Number).Compare);
sortlist = list1.ToEnumerable().ToArray();
Array.Sort(sortlist, new LambdaComparer<Thing>(OrderedComparer<Thing>.OrderBy(x => x.Number).Compare));
CollectionAssert.AreEqual(sortlist.Take(5), col);
col.SetComparer(OrderedComparer<Thing>.OrderBy(x => x.CreatedAt).Compare);
sortlist = list1.ToEnumerable().ToArray();
Array.Sort(sortlist, new LambdaComparer<Thing>(OrderedComparer<Thing>.OrderBy(x => x.CreatedAt).Compare));
CollectionAssert.AreEqual(sortlist.Take(5), col);
col.SetComparer(OrderedComparer<Thing>.OrderByDescending(x => x.Title).Compare);
sortlist = list1.ToEnumerable().ToArray();
Array.Sort(sortlist, new LambdaComparer<Thing>(OrderedComparer<Thing>.OrderByDescending(x => x.Title).Compare));
CollectionAssert.AreEqual(sortlist.Take(5), col);
col.SetComparer(OrderedComparer<Thing>.OrderBy(x => x.Title).Compare);
sortlist = list1.ToEnumerable().ToArray();
Array.Sort(sortlist, new LambdaComparer<Thing>(OrderedComparer<Thing>.OrderBy(x => x.Title).Compare));
CollectionAssert.AreEqual(sortlist.Take(5), col);
col.Dispose();
}
示例11: Removing
public void Removing()
{
var source = new Subject<Thing>();
var col = new TrackingCollection<Thing>(
source,
OrderedComparer<Thing>.OrderBy(x => x.UpdatedAt).Compare,
(item, position, list) => (position > 2 && position < 5) || (position > 6 && position < 8))
{ ProcessingDelay = TimeSpan.Zero };
var count = 0;
var expectedCount = 0;
var evt = new ManualResetEvent(false);
col.Subscribe(t =>
{
if (++count == expectedCount)
evt.Set();
}, () => { });
expectedCount = 11;
Add(source, GetThing(0, 0));
Add(source, GetThing(1, 1));
Add(source, GetThing(2, 2));
Add(source, GetThing(3, 3));
Add(source, GetThing(4, 4));
Add(source, GetThing(5, 5));
Add(source, GetThing(6, 6));
Add(source, GetThing(7, 7));
Add(source, GetThing(8, 8));
Add(source, GetThing(9, 9));
Add(source, GetThing(10, 10));
evt.WaitOne();
evt.Reset();
CollectionAssert.AreEqual(col, new List<Thing> {
GetThing(3, 3),
GetThing(4, 4),
GetThing(7, 7),
});
expectedCount = 12;
col.RemoveItem(GetThing(2));
evt.WaitOne();
evt.Reset();
CollectionAssert.AreEqual(col, new List<Thing> {
GetThing(4, 4),
GetThing(5, 5),
GetThing(8, 8),
});
expectedCount = 13;
col.RemoveItem(GetThing(5));
evt.WaitOne();
evt.Reset();
CollectionAssert.AreEqual(col, new List<Thing> {
GetThing(4, 4),
GetThing(6, 6),
GetThing(9, 9),
});
col.SetFilter(null);
expectedCount = 14;
col.RemoveItem(GetThing(100)); // this one won't result in a new element from the observable
col.RemoveItem(GetThing(10));
evt.WaitOne();
evt.Reset();
Assert.AreEqual(8, col.Count);
CollectionAssert.AreEqual(col, new List<Thing> {
GetThing(0, 0),
GetThing(1, 1),
GetThing(3, 3),
GetThing(4, 4),
GetThing(6, 6),
GetThing(7, 7),
GetThing(8, 8),
GetThing(9, 9),
});
col.Dispose();
}
示例12: ChangingComparers
public void ChangingComparers()
{
var source = new Subject<Thing>();
var col = new TrackingCollection<Thing>(source, OrderedComparer<Thing>.OrderBy(x => x.CreatedAt).Compare) { ProcessingDelay = TimeSpan.Zero };
var count = 0;
var evt = new ManualResetEvent(false);
var list1 = new List<Thing> {
GetThing(1, 1, 9),
GetThing(2, 2, 8),
GetThing(3, 3, 7),
GetThing(4, 4, 6),
GetThing(5, 5, 5),
GetThing(6, 6, 4),
GetThing(7, 7, 3),
GetThing(8, 8, 2),
GetThing(9, 9, 1),
};
col.Subscribe(t =>
{
if (++count == list1.Count)
evt.Set();
}, () => { });
foreach (var l in list1)
Add(source, l);
evt.WaitOne();
evt.Reset();
CollectionAssert.AreEqual(col, list1);
col.SetComparer(null);
CollectionAssert.AreEqual(col, list1.Reverse<Thing>().ToArray());
col.Dispose();
}
示例13: WaitNotificationTest
public static void WaitNotificationTest()
{
ThreadTestHelpers.RunTestInBackgroundThread(() =>
{
var tsc = new TestSynchronizationContext();
SynchronizationContext.SetSynchronizationContext(tsc);
Assert.Same(tsc, SynchronizationContext.Current);
var e = new ManualResetEvent(false);
tsc.WaitAction = () => e.Set();
Assert.False(tsc.IsWaitNotificationRequired());
Assert.False(e.WaitOne(0));
tsc.SetWaitNotificationRequired();
Assert.True(tsc.IsWaitNotificationRequired());
Assert.True(e.WaitOne(0));
var mres = new ManualResetEventSlim();
tsc.WaitAction = () => mres.Set();
mres.Reset();
mres.CheckedWait();
e.Reset();
tsc.WaitAction = () => e.Set();
SynchronizationContext.SetSynchronizationContext(new TestSynchronizationContext());
Assert.False(e.WaitOne(0));
SynchronizationContext.SetSynchronizationContext(tsc);
Assert.True(e.WaitOne(0));
e.Reset();
e.CheckedWait();
e.Reset();
var lockObj = new object();
var lockAcquiredFromBackground = new AutoResetEvent(false);
Action waitForThread;
Thread t =
ThreadTestHelpers.CreateGuardedThread(out waitForThread, () =>
{
lock (lockObj)
{
lockAcquiredFromBackground.Set();
e.CheckedWait();
}
});
t.IsBackground = true;
t.Start();
lockAcquiredFromBackground.CheckedWait();
Assert.True(Monitor.TryEnter(lockObj, ThreadTestHelpers.UnexpectedTimeoutMilliseconds));
Monitor.Exit(lockObj);
waitForThread();
e.Reset();
var m = new Mutex();
t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, () =>
{
m.CheckedWait();
try
{
lockAcquiredFromBackground.Set();
e.CheckedWait();
}
finally
{
m.ReleaseMutex();
}
});
t.IsBackground = true;
t.Start();
lockAcquiredFromBackground.CheckedWait();
m.CheckedWait();
m.ReleaseMutex();
waitForThread();
});
}
示例14: RemovingFirstItemWithFilterWorks
public void RemovingFirstItemWithFilterWorks()
{
var source = new Subject<Thing>();
ITrackingCollection<Thing> col = new TrackingCollection<Thing>(
Observable.Range(0, 5).Select(x => GetThing(x, x)),
OrderedComparer<Thing>.OrderBy(x => x.UpdatedAt).Compare,
(item, position, list) => true);
col.ProcessingDelay = TimeSpan.Zero;
var count = 0;
var expectedCount = 5;
var evt = new ManualResetEvent(false);
col.Subscribe(t =>
{
if (++count == expectedCount)
evt.Set();
}, () => { });
Assert.True(evt.WaitOne(40));
evt.Reset();
expectedCount = 6;
col.RemoveItem(GetThing(0));
Assert.True(evt.WaitOne(40));
evt.Reset();
CollectionAssert.AreEqual(col, Enumerable.Range(1, 4).Select(x => GetThing(x, x)));
col.Dispose();
}
示例15: ExpiredIndexClearsItems
public async Task ExpiredIndexClearsItems()
{
var expected = 5;
var username = "octocat";
var reponame = "repo";
var cache = new InMemoryBlobCache();
var apiClient = Substitute.For<IApiClient>();
var modelService = new ModelService(apiClient, cache, Substitute.For<IAvatarProvider>());
var user = CreateOctokitUser(username);
apiClient.GetUser().Returns(Observable.Return(user));
apiClient.GetOrganizations().Returns(Observable.Empty<Organization>());
var act = modelService.GetAccounts().ToEnumerable().First().First();
var repo = Substitute.For<ISimpleRepositoryModel>();
repo.Name.Returns(reponame);
repo.CloneUrl.Returns(new UriString("https://github.com/" + username + "/" + reponame));
var indexKey = string.Format(CultureInfo.InvariantCulture, "{0}|{1}|pr", user.Login, repo.Name);
var prcache = Enumerable.Range(1, expected)
.Select(id => CreatePullRequest(user, id, ItemState.Open, "Cache " + id, DateTimeOffset.UtcNow, DateTimeOffset.UtcNow, 0));
// seed the cache
prcache
.Select(item => new ModelService.PullRequestCacheItem(item))
.Select(item => item.Save<ModelService.PullRequestCacheItem>(cache, indexKey).ToEnumerable().First())
.SelectMany(item => CacheIndex.AddAndSaveToIndex(cache, indexKey, item).ToEnumerable())
.ToList();
// expire the index
var indexobj = await cache.GetObject<CacheIndex>(indexKey);
indexobj.UpdatedAt = DateTimeOffset.UtcNow - TimeSpan.FromMinutes(6);
await cache.InsertObject(indexKey, indexobj);
var prlive = Observable.Range(5, expected)
.Select(id => CreatePullRequest(user, id, ItemState.Open, "Live " + id, DateTimeOffset.UtcNow, DateTimeOffset.UtcNow, 0))
.DelaySubscription(TimeSpan.FromMilliseconds(10));
apiClient.GetPullRequestsForRepository(user.Login, repo.Name).Returns(prlive);
await modelService.InsertUser(new AccountCacheItem(user));
var col = modelService.GetPullRequests(repo);
col.ProcessingDelay = TimeSpan.Zero;
var count = 0;
var evt = new ManualResetEvent(false);
col.Subscribe(t =>
{
// we get all the items from the cache (items 1-5), all the items from the live (items 5-9),
// and 4 deletions (items 1-4) because the cache expired the items that were not
// a part of the live data
if (++count == 14)
evt.Set();
}, () => { });
evt.WaitOne();
evt.Reset();
Assert.Equal(5, col.Count);
Assert.Collection(col,
t => { Assert.True(t.Title.StartsWith("Live")); Assert.Equal(5, t.Number); },
t => { Assert.True(t.Title.StartsWith("Live")); Assert.Equal(6, t.Number); },
t => { Assert.True(t.Title.StartsWith("Live")); Assert.Equal(7, t.Number); },
t => { Assert.True(t.Title.StartsWith("Live")); Assert.Equal(8, t.Number); },
t => { Assert.True(t.Title.StartsWith("Live")); Assert.Equal(9, t.Number); }
);
}