本文整理汇总了C#中System.Threading.CountdownEvent.AddCount方法的典型用法代码示例。如果您正苦于以下问题:C# CountdownEvent.AddCount方法的具体用法?C# CountdownEvent.AddCount怎么用?C# CountdownEvent.AddCount使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Threading.CountdownEvent
的用法示例。
在下文中一共展示了CountdownEvent.AddCount方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: AddCount_Invalid
public void AddCount_Invalid ()
{
var ev = new CountdownEvent (1);
try {
ev.AddCount (0);
Assert.Fail ("#1");
} catch (ArgumentOutOfRangeException) {
}
try {
ev.AddCount (-1);
Assert.Fail ("#2");
} catch (ArgumentOutOfRangeException) {
}
}
示例2: Main
static void Main(string[] args)
{
var customers = Enumerable.Range(1, 20);
using (var countdown = new CountdownEvent(1))
{
foreach (var customer in customers)
{
int currentCustomer = customer;
countdown.AddCount();
ThreadPool.QueueUserWorkItem(delegate
{
BuySomeStuff(currentCustomer);
countdown.Signal();
});
}
countdown.Signal();
countdown.Wait();
}
Console.WriteLine("All Customers finished shopping...");
Console.ReadKey();
}
示例3: MessageQueueThread_HandlesException
public async Task MessageQueueThread_HandlesException()
{
var exception = new Exception();
var countdown = new CountdownEvent(1);
var handler = new Action<Exception>(ex =>
{
Assert.AreSame(exception, ex);
countdown.Signal();
});
var uiThread = await CallOnDispatcherAsync(() => MessageQueueThread.Create(MessageQueueThreadSpec.DispatcherThreadSpec, handler));
var backgroundThread = MessageQueueThread.Create(MessageQueueThreadSpec.Create("background", MessageQueueThreadKind.BackgroundSingleThread), handler);
var taskPoolThread = MessageQueueThread.Create(MessageQueueThreadSpec.Create("any", MessageQueueThreadKind.BackgroundAnyThread), handler);
var queueThreads = new[]
{
uiThread,
backgroundThread,
taskPoolThread
};
countdown.AddCount(queueThreads.Length - 1);
foreach (var queueThread in queueThreads)
{
queueThread.RunOnQueue(() => { throw exception; });
}
Assert.IsTrue(countdown.Wait(5000));
}
示例4: ExecuteLevel
protected override void ExecuteLevel(IList<Computation> computationsOfLevel)
{
using (var countEvent = new CountdownEvent(1))
{
foreach (var item in computationsOfLevel)
{
var cc = item.Context as ParallelComputationContext;
if (cc != null)
{
countEvent.AddCount();
cc.RunTransform(() =>
{
item.Transform();
countEvent.Signal();
});
}
else
{
countEvent.Signal();
countEvent.Wait();
item.Transform();
countEvent.Reset();
}
OnComputationCompleted(new ComputationEventArgs(item));
}
countEvent.Signal();
countEvent.Wait();
}
}
示例5: OperationContext
public OperationContext(CountdownEvent countdownEvent, ConcurrentOperationManager manager)
{
_countdownEvent = countdownEvent;
_countdownEvent.AddCount();
manager.OnOperationContextCreated(EventArgs.Empty);
if(manager._isDisposed)
{
Dispose();
throw new ObjectDisposedException(manager._owningType);
}
}
开发者ID:hjb417,项目名称:rabbitmq-wcf-transports,代码行数:11,代码来源:ConcurrentOperationManager+OperationContext.cs
示例6: ScanIPs
public static void ScanIPs()
{
//string hostName = Dns.GetHostName(); // Retrive the Name of HOST
//Console.WriteLine(hostName);
// Get the IP
//string myIP = Dns.GetHostByName(hostName).AddressList[0].ToString();
string myIP = "192.168.1.1";
var bytes = IPAddress.Parse(myIP).GetAddressBytes();
// set the value here
bytes[3] = 0;
IPAddress ipAddress = new IPAddress(bytes);
var IPaddress1 = IPAddress.Parse(myIP).GetAddressBytes()[0].ToString() + "." + IPAddress.Parse(myIP).GetAddressBytes()[1].ToString() + "." + IPAddress.Parse(myIP).GetAddressBytes()[2].ToString() + ".";
Console.WriteLine("My IP Address is :" + myIP);
Console.WriteLine("Network :" + IPaddress1);
//Console.ReadLine();
countdown = new CountdownEvent(1);
Stopwatch sw = new Stopwatch();
sw.Start();
//string ipBase = "10.0.0.";
for (int i = 1; i < 255; i++)
{
string ip = IPaddress1 + i.ToString();
Ping p = new Ping();
p.PingCompleted += new PingCompletedEventHandler(p_PingCompleted);
countdown.AddCount();
p.SendAsync(ip, 100, ip);
}
countdown.Signal();
countdown.Wait();
sw.Stop();
TimeSpan span = new TimeSpan(sw.ElapsedTicks);
//Console.WriteLine("Took {0} milliseconds. {1} hosts active.", sw.ElapsedMilliseconds, upCount);
//Console.WriteLine("\nPress any key to continue...");
//Console.ReadKey();
}
示例7: IndexOnPagesInDB_IAMLAZY
private static void IndexOnPagesInDB_IAMLAZY()
{
foreach (var page in database.GetAllPages())
{
ToBeIndexedQueue.Enqueue(new Tuple<PrettyURL, string, DateTime>(new PrettyURL(page.url), page.html, DateTime.Now));
}
CountdownEvent CTE = new CountdownEvent(1);
var indexer = new MainIndexer(stopWords, charsToRemove, ToBeIndexedQueue, CTE);
Thread indexerThread = new Thread(() => indexer.CreateInverseIndexWriteToDB(true));
CTE.AddCount();
indexerThread.Start();
CTE.Signal();
CTE.Wait();
}
示例8: AddCount_HasBeenSet
public void AddCount_HasBeenSet()
{
var ev = new CountdownEvent(0);
try
{
ev.AddCount(1);
Assert.Fail("#1");
}
catch (InvalidOperationException)
{
}
ev = new CountdownEvent(1);
Assert.IsTrue(ev.Signal(), "#2");
try
{
ev.AddCount(1);
Assert.Fail("#3");
}
catch (InvalidOperationException)
{
}
}
示例9: RunCountdownEventTest2_Exceptions
public static void RunCountdownEventTest2_Exceptions()
{
CountdownEvent cde = null;
Assert.Throws<ArgumentOutOfRangeException>(() => cde = new CountdownEvent(-1));
// Failure Case: Constructor didn't throw AORE when -1 passed
cde = new CountdownEvent(1);
Assert.Throws<ArgumentOutOfRangeException>(() => cde.Signal(0));
// Failure Case: Signal didn't throw AORE when 0 passed
cde = new CountdownEvent(0);
Assert.Throws<InvalidOperationException>(() => cde.Signal());
// Failure Case: Signal didn't throw IOE when the count is zero
cde = new CountdownEvent(1);
Assert.Throws<InvalidOperationException>(() => cde.Signal(2));
// Failure Case: Signal didn't throw IOE when the signal count > current count
Assert.Throws<ArgumentOutOfRangeException>(() => cde.AddCount(0));
// Failure Case: AddCount didn't throw AORE when 0 passed
cde = new CountdownEvent(0);
Assert.Throws<InvalidOperationException>(() => cde.AddCount(1));
// Failure Case: AddCount didn't throw IOE when the count is zero
cde = new CountdownEvent(int.MaxValue - 10);
Assert.Throws<InvalidOperationException>(() => cde.AddCount(20));
// Failure Case: AddCount didn't throw IOE when the count > int.Max
cde = new CountdownEvent(2);
Assert.Throws<ArgumentOutOfRangeException>(() => cde.Reset(-1));
// Failure Case: Reset didn't throw AORE when the count is zero
Assert.Throws<ArgumentOutOfRangeException>(() => cde.Wait(-2));
// Failure Case: Wait(int) didn't throw AORE when the totalmilliseconds < -1
Assert.Throws<ArgumentOutOfRangeException>(() => cde.Wait(TimeSpan.FromDays(-1)));
// Failure Case: FAILED. Wait(TimeSpan) didn't throw AORE when the totalmilliseconds < -1
Assert.Throws<ArgumentOutOfRangeException>(() => cde.Wait(TimeSpan.MaxValue));
// Failure Case: Wait(TimeSpan, CancellationToken) didn't throw AORE when the totalmilliseconds > int.max
Assert.Throws<ArgumentOutOfRangeException>(() => cde.Wait(TimeSpan.FromDays(-1), new CancellationToken()));
// Failure Case: Wait(TimeSpan) didn't throw AORE when the totalmilliseconds < -1
Assert.Throws<ArgumentOutOfRangeException>(() => cde.Wait(TimeSpan.MaxValue, new CancellationToken()));
// Failure Case: Wait(TimeSpan, CancellationToken) didn't throw AORE when the totalmilliseconds > int.max
cde.Dispose();
Assert.Throws<ObjectDisposedException>(() => cde.Wait());
// Failure Case: Wait() didn't throw ODE after Dispose
}
示例10: DownloadZipItems
private void DownloadZipItems(List<ItemStatus> items)
{
var todo = items.Where(e => e.RequireDownload && !string.IsNullOrEmpty(e.ZipUrl)).ToList();
if (todo.Count == 0)
return;
#if PARALLEL
CountdownEvent countdown = new CountdownEvent(1);
foreach (var item in todo)
{
var cli = new WebClient();
cli.DownloadFileCompleted += OnDownloadZipItemCompleted;
Utils.WriteLine("Downloading " + item.ZipUrl + " ...");
countdown.AddCount(1);
var file = Path.Combine(launcher.WorkshopFolder, item.FolderName + ".zip");
File.Delete(file);
cli.DownloadFileAsync(new Uri(item.ZipUrl), file, new Tuple<string, ItemStatus, CountdownEvent>(file, item, countdown));
}
countdown.Signal();
countdown.Wait();
#else
int i = 0;
foreach (var item in todo)
{
++i;
Utils.Write(item.ZipUrl + " (" + i + "/" + todo.Count + ") ... ");
var dir = Path.Combine(launcher.WorkshopFolder, item.FolderName);
DateTime remoteDate;
using (var cli = new HttpClient())
{
var req = new HttpRequestMessage();
req.Method = HttpMethod.Head;
req.RequestUri = new Uri(item.ZipUrl);
var task = cli.SendAsync(req);
if (!task.Wait(1000))
{
Utils.WriteLine("^1timeout^7");
continue;
}
remoteDate = GetDateHeader(task.Result);
}
var localDate = File.GetLastWriteTimeUtc(dir);
if (remoteDate != DateTime.MinValue && Directory.Exists(dir) && Math.Abs((remoteDate - localDate).TotalSeconds) < 1)
{
Utils.WriteLine("up-to-date");
continue;
}
Utils.WriteLine("downloading");
var file = dir + ".zip";
File.Delete(file);
var wc = new WebClient();
AsyncCompletedEventArgs args;
try
{
wc.DownloadFile(new Uri(item.ZipUrl), file);
args = new AsyncCompletedEventArgs(null, false, new Tuple<string, ItemStatus, CountdownEvent, DateTime>(file, item, null, remoteDate));
}
catch (Exception ex)
{
args = new AsyncCompletedEventArgs(ex, false, new Tuple<string, ItemStatus, CountdownEvent, DateTime>(file, item, null, remoteDate));
}
OnDownloadZipItemCompleted(wc, args);
}
#endif
}
示例11: Scanner
public static void Scanner()
{
//Get's preferred outbound IP address
string localIP;
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0))
{
socket.Connect("10.0.2.4", 65530);
IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint;
localIP = endPoint.Address.ToString();
}
//Console.WriteLine(localIP);
var bytes = IPAddress.Parse(localIP).GetAddressBytes();
bytes[3] = 0;
IPAddress ipAddress = new IPAddress(bytes);
var IPaddress1 = IPAddress.Parse(localIP).GetAddressBytes()[0].ToString() + "." + IPAddress.Parse(localIP).GetAddressBytes()[1].ToString() + "." + IPAddress.Parse(localIP).GetAddressBytes()[2].ToString() + ".";
// Console.WriteLine(bytes);
//Console.WriteLine(ipAddress);
//Console.WriteLine(IPaddress1);
//Console.ReadLine();
//Console.WriteLine("Scanning Network");
countdown = new CountdownEvent(1);
Stopwatch sw = new Stopwatch();
sw.Start();
//string ipBase = "10.0.0.";
for (int i = 1; i < 255; i++)
{
string ip = IPaddress1 + i.ToString();
Ping p = new Ping();
p.PingCompleted += new PingCompletedEventHandler(p_PingCompleted);
countdown.AddCount();
p.SendAsync(ip, 100, ip);
}
countdown.Signal();
countdown.Wait();
sw.Stop();
TimeSpan span = new TimeSpan(sw.ElapsedTicks);
var list = strings.Keys.ToList();
list.Sort();
}
示例12: UpdateObjectsMT
/// <summary>
/// Повикува Update на секој објект во посебен thread. Се користи ThreadPool.
/// </summary>
/// <param name="gameObjects"></param>
private void UpdateObjectsMT(IList<IGameObject> gameObjects)
{
//CountdownEvent
/* http://msdn.microsoft.com/en-us/library/dd997365.aspx */
//не може паралелно да се одвива оваа операција
//паралелен дел
using (CountdownEvent e = new CountdownEvent(1))
{
// fork work:
foreach (IGameObject obj in gameObjects)
{
// Dynamically increment signal count.
e.AddCount();
ThreadPool.QueueUserWorkItem(delegate(object gameObject)
{
try
{
UpdateObject((IGameObject)gameObject);
}
finally
{
e.Signal();
}
},
obj);
}
e.Signal();
// The first element could be run on this thread.
// Join with work.
e.Wait();
}
InitQuadTree(gameObjects);
InitCollisionArguments(gameObjects);
//паралелен дел
using (CountdownEvent e = new CountdownEvent(1))
{
// fork work:
foreach (IGameObject obj in gameObjects)
{
// Dynamically increment signal count.
e.AddCount();
ThreadPool.QueueUserWorkItem(delegate(object gameObject)
{
try
{
CheckForCollisions((IGameObject)gameObject);
}
finally
{
e.Signal();
}
},
obj);
}
e.Signal();
// The first element could be run on this thread.
// Join with work.
e.Wait();
}
//паралелен дел
using (CountdownEvent e = new CountdownEvent(1))
{
// fork work:
foreach (IGameObject obj in gameObjects)
{
// Dynamically increment signal count.
e.AddCount();
ThreadPool.QueueUserWorkItem(delegate(object gameObject)
{
try
{
PassCollisionArgumentsToObject((IGameObject)gameObject);
}
finally
{
e.Signal();
}
},
obj);
}
e.Signal();
// The first element could be run on this thread.
// Join with work.
e.Wait();
}
//.........这里部分代码省略.........
示例13: ExecuteThreadedCompilePass
private void ExecuteThreadedCompilePass(int threads)
{
using (var finished = new CountdownEvent(1))
{
for (int threadID = 0; threadID < threads; threadID++)
{
finished.AddCount();
int tid = threadID + 1;
ThreadPool.QueueUserWorkItem(
new WaitCallback(delegate
{
//try
//{
CompileWorker(tid);
//}
//catch (Exception e)
//{
// this.CompilerTrace.NewCompilerTraceEvent(CompilerEvent.Exception, e.ToString(), threadID);
//}
//finally
//{
finished.Signal();
//}
}
));
}
finished.Signal();
finished.Wait();
}
}
示例14: unionButton_Click
// perform union on currently selected layer
private void unionButton_Click(object sender, EventArgs e)
{
toolBuilder.addHeader("Union");
// textbox for new layername
TextBox textbox = toolBuilder.addTextboxWithCaption("New layername:");
Label errorLabel = toolBuilder.addErrorLabel();
Button button = toolBuilder.addButton("Union", (Layer l) =>
{
// user has not set new layername
if (textbox.Text.Length == 0)
{
toolBuilder.setError("Provide name");
return;
}
// create temporary layer
Layer copyLayer = new Layer(l.Name);
copyLayer.Boundingbox = new Envelope(l.Boundingbox);
copyLayer.createQuadTree();
// copy all features to temp layer
foreach (Feature f in l.Features.Values)
copyLayer.addFeature(new Feature((IGeometry)f.Geometry.Clone(), f.ID));
// create new layer with same boundingbox
Layer newLayer = new Layer(textbox.Text);
newLayer.Boundingbox = new Envelope(l.Boundingbox);
newLayer.createQuadTree();
// init progress bar
int numFeatures = copyLayer.Features.Values.Count;
progressLabel.Text = "Performing union";
progressBar.Minimum = 0;
progressBar.Maximum = numFeatures;
BackgroundWorker bw = new BackgroundWorker();
bw.WorkerReportsProgress = true;
// perform merge in another thread
bw.DoWork += (object wsender, DoWorkEventArgs we) =>
{
// threadsafe list of merged features
ConcurrentBag<Feature> newFeatures = new ConcurrentBag<Feature>();
var finished = new CountdownEvent(1);
Object _lock = new object();
// create thread function
var merge = new WaitCallback((state) =>
{
Random rnd = new Random();
while (true)
{
Feature f;
lock (_lock)
{
// break if no more features
if (copyLayer.Features.Count == 0)
break;
// get random index
int index = rnd.Next(copyLayer.Features.Count);
// get corresponding random feature
f = copyLayer.Features[copyLayer.Features.Keys.ToList()[index]];
// remove feature from layer
copyLayer.delFeature(f);
}
f.ID = -1;
while (true)
{
List<Feature> intersects;
// aquire lock to avoid race conditions
lock (_lock)
{
// get all features intersecting feature
intersects = copyLayer.getWithin(f.Geometry);
// remove features from layer
foreach (Feature intersect in intersects)
copyLayer.delFeature(intersect);
}
// if no intersects, no merging is necessary
if (intersects.Count == 0)
break;
// merge all features
foreach (Feature intersect in intersects)
{
f = new Feature(f.Geometry.Union(intersect.Geometry));
bw.ReportProgress(1);
}
}
// add feature to list of new features
newFeatures.Add(f);
}
finished.Signal();
});
// spawn eight threads, this is not always optimal but a good approximation
for (int i = 0; i < 8; i++)
{
finished.AddCount();
ThreadPool.QueueUserWorkItem(merge);
}
finished.Signal();
finished.Wait();
//.........这里部分代码省略.........
示例15: CurrentCountTestCase
public void CurrentCountTestCase()
{
var evt = new CountdownEvent (5);
Assert.AreEqual(5, evt.CurrentCount, "#1");
evt.AddCount();
Assert.AreEqual(6, evt.CurrentCount, "#2");
evt.TryAddCount(2);
Assert.AreEqual(8, evt.CurrentCount, "#3");
evt.Signal(4);
Assert.AreEqual(4, evt.CurrentCount, "#4");
evt.Reset();
Assert.AreEqual(5, evt.CurrentCount, "#5");
}