本文整理汇总了C#中BlockingCollection.GetConsumingEnumerable方法的典型用法代码示例。如果您正苦于以下问题:C# BlockingCollection.GetConsumingEnumerable方法的具体用法?C# BlockingCollection.GetConsumingEnumerable怎么用?C# BlockingCollection.GetConsumingEnumerable使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类BlockingCollection
的用法示例。
在下文中一共展示了BlockingCollection.GetConsumingEnumerable方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
static void Main(string[] args)
{
BlockingCollection<string> col = new BlockingCollection<string>();
Task read = Task.Run(() =>
{
foreach (var v in col.GetConsumingEnumerable())
{
Console.WriteLine(v);
}
});
Console.WriteLine("Enter white space to break");
Task write = Task.Run(() =>
{
while (true)
{
string s = Console.ReadLine();
if (string.IsNullOrWhiteSpace(s))
{
break;
}
col.Add(s);
}
});
write.Wait();
Console.Write("Press a key to exit");
Console.ReadKey();
}
示例2: ReadDT
private void ReadDT()
{
BlockingCollection<string> lines = new BlockingCollection<string>();
var stage1 = Task.Run(() =>
{
using (StreamReader sr = new StreamReader("text.txt"))
{
string s;
while ((s = sr.ReadLine()) != null)
lines.Add(s);
}
lines.CompleteAdding();
});
var stage2 = Task.Run(() =>
{
int i = 0;
dataGridView1.Invoke((Action)(() => dataGridView1.SuspendLayout()));
foreach (string line in lines.GetConsumingEnumerable())
{
dataGridView1.Invoke((Action)(() => dataGridView1.Rows.Add(line.Split(';'))));
dataGridView1.Invoke((Action)(() => dataGridView1.Rows[i].HeaderCell.Value = i.ToString()));
i++;
}
dataGridView1.Invoke((Action)(() => dataGridView1.ResumeLayout(false)));
});
Task.WaitAll(stage1, stage2);
}
示例3: Main
static void Main(string[] args)
{
BlockingCollection<String> col = new BlockingCollection<string>();
Task read = Task.Run(() =>
{
foreach (var item in col.GetConsumingEnumerable())
{
Console.WriteLine(item);
}
});
Task write = Task.Run(() =>
{
while (true)
{
string s = Console.ReadLine();
if (string.IsNullOrWhiteSpace(s))
{
break;
}
col.Add(s);
}
});
write.Wait();
}
示例4: when_consuming_enumerable_then_succeeds
public void when_consuming_enumerable_then_succeeds()
{
var bytes = new BlockingCollection<byte>();
var incoming = bytes.GetConsumingEnumerable().ToObservable(TaskPoolScheduler.Default);
var messages = from header in incoming.Buffer(4)
let length = BitConverter.ToInt32(header.ToArray(), 0)
let body = incoming.Take(length)
select Encoding.UTF8.GetString(body.ToEnumerable().ToArray());
messages.Subscribe(s => Console.Write(s));
var message = "hello";
BitConverter.GetBytes(message.Length).Concat(Encoding.UTF8.GetBytes(message)).ToList().ForEach(b => bytes.Add(b));
message = "world";
BitConverter.GetBytes(message.Length).Concat(Encoding.UTF8.GetBytes(message)).ToList().ForEach(b => bytes.Add(b));
Thread.Sleep(2000);
Console.WriteLine(bytes.Count);
}
示例5: StaTaskScheduler
/// <summary>Initializes a new instance of the StaTaskScheduler class with the specified concurrency level.</summary>
/// <param name="numberOfThreads">The number of threads that should be created and used by this scheduler.</param>
public StaTaskScheduler(int numberOfThreads)
{
// Validate arguments
if (numberOfThreads < 1)
throw new ArgumentOutOfRangeException("concurrencyLevel");
// Initialize the tasks collection
_tasks = new BlockingCollection<Task>();
// Create the threads to be used by this scheduler
_threads = Enumerable.Range(0, numberOfThreads).Select(i =>
{
var thread = new Thread(() =>
{
// Continually get the next task and try to execute it.
// This will continue until the scheduler is disposed and no more tasks remain.
foreach (var t in _tasks.GetConsumingEnumerable())
{
if (!TryExecuteTask(t))
{
System.Diagnostics.Debug.Assert(t.IsCompleted, "Can't run, not completed");
}
}
});
thread.IsBackground = true;
thread.SetApartmentState(ApartmentState.STA);
return thread;
}).ToImmutableArray();
// Start all of the threads
foreach (var thread in _threads)
{
thread.Start();
}
}
示例6: StaTaskScheduler
/// <summary>Initializes a new instance of the StaTaskScheduler class with the specified concurrency level.</summary>
/// <param name="numberOfThreads">The number of threads that should be created and used by this scheduler.</param>
public StaTaskScheduler(int numberOfThreads)
{
// Validate arguments
if (numberOfThreads < 1) throw new ArgumentOutOfRangeException("concurrencyLevel");
// Initialize the tasks collection
_tasks = new BlockingCollection<Task>();
// Create the threads to be used by this scheduler
_threads = Enumerable.Range(0, numberOfThreads).Select(i =>
{
var thread = new Thread(() =>
{
// Continually get the next task and try to execute it.
// This will continue until the scheduler is disposed and no more tasks remain.
foreach (var t in _tasks.GetConsumingEnumerable())
{
TryExecuteTask(t);
}
});
thread.IsBackground = true;
thread.SetApartmentState(ApartmentState.STA);
return thread;
}).ToList();
// Start all of the threads
_threads.ForEach(t => t.Start());
}
示例7: Do
/// <summary>
/// Do the specified input and output.
/// </summary>
/// <param name="input">Input.</param>
/// <param name="output">Output.</param>
public void Do(BlockingCollection<ISkeleton> input, BlockingCollection<ISkeleton> output)
{
var skeletons = new List<ISkeleton>();
try
{
foreach (var skeleton in input.GetConsumingEnumerable())
{
skeletons.Add(skeleton);
if (skeletons.Count < 3)
{
continue;
}
var first = skeletons.First();
var tail = skeletons.Skip(1);
foreach (var joint in first.Joints)
{
var tailJoints = tail.Select(s => s.GetJoint(joint.JointType));
joint.Point = Mean(new List<Vector3> { joint.Point }.Concat(tailJoints.Select(j => j.Point)).ToList());
joint.Orientation = Mean(new List<Vector4> { joint.Orientation }.Concat(tailJoints.Select(j => j.Orientation)).ToList());
first.UpdateSkeleton(joint.JointType, joint);
}
output.Add(first);
skeletons.Clear();
}
}
finally
{
output.CompleteAdding();
}
}
示例8: Execute
public override IEnumerable<Row> Execute(IEnumerable<Row> rows) {
var blockingCollection = new BlockingCollection<Row>();
var count = _operations.Count;
if (count == 0) {
yield break;
}
Debug("Creating tasks for {0} operations.", count);
var tasks = _operations.Select(currentOp =>
Task.Factory.StartNew(() => {
try {
foreach (var row in currentOp.Execute(null)) {
blockingCollection.Add(row);
}
}
finally {
if (Interlocked.Decrement(ref count) == 0) {
blockingCollection.CompleteAdding();
}
}
})).ToArray();
foreach (var row in blockingCollection.GetConsumingEnumerable()) {
yield return row;
}
Task.WaitAll(tasks); // raise any exception that were raised during execution
}
示例9: StaTaskScheduler
public StaTaskScheduler(int numberOfThreads)
{
if (numberOfThreads < 1)
throw new ArgumentOutOfRangeException("concurrencyLevel");
_tasks = new BlockingCollection<Task>();
_threads = Enumerable.Range(0, numberOfThreads).Select(i =>
{
var thread = new Thread(() =>
{
foreach (var t in
_tasks.GetConsumingEnumerable())
{
TryExecuteTask(t);
}
})
{
IsBackground = true
};
thread.SetApartmentState(ApartmentState.STA);
return thread;
}).ToList();
_threads.ForEach(t => t.Start());
}
示例10: Main
public static void Main(string[] args)
{
BlockingCollection<string> collection = new BlockingCollection<string>();
Task read = Task.Run(() =>
{
foreach (string v in collection.GetConsumingEnumerable())
{
Console.WriteLine(v);
}
});
Task write = Task.Run(() =>
{
while (true)
{
string s = Console.ReadLine();
if (string.IsNullOrWhiteSpace(s))
{
collection.CompleteAdding();
break;
}
collection.Add(s);
}
});
write.Wait();
}
示例11: Run
public static void Run()
{
int size = 10;
BlockingCollection<int> col = new BlockingCollection<int>(size/3);
Task read = Task.Run(() =>
{
foreach(var item in col.GetConsumingEnumerable())
{
Console.WriteLine("Read " + item);
}
});
Task write = Task.Run(() =>
{
foreach(int i in Enumerable.Range(1, size))
{
Console.WriteLine("adding " + i);
col.Add(i);
}
col.CompleteAdding();
});
write.Wait();
read.Wait();
}
示例12: Main
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
BlockingCollection<String> col = new BlockingCollection<string>();
Task read = Task.Run(() =>
{
foreach (String v in col.GetConsumingEnumerable())
Console.WriteLine(v);
});
Task write = Task.Run(() =>
{
while (true)
{
String s = Console.ReadLine();
if (String.IsNullOrWhiteSpace(s)) break;
col.Add(s);
}
});
write.Wait();
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
示例13: LoadBuildersWithTasks
public static List<Builder> LoadBuildersWithTasks(int numberOfBuilders)
{
BlockingCollection<Builder> buildersToLoad = new BlockingCollection<Builder>();
BlockingCollection<Builder> loadedBuilders = new BlockingCollection<Builder>();
for (int i = 0; i < numberOfBuilders; i++)
{
buildersToLoad.Add(new Builder { Name = "Builder" + i, Status = "Status" + i });
}
buildersToLoad.CompleteAdding();
Task loader1 = Task.Factory.StartNew(() =>
{
foreach (Builder item in buildersToLoad.GetConsumingEnumerable())
{
Thread.Sleep(1000);
loadedBuilders.Add(item);
}
}, TaskCreationOptions.LongRunning);
Task loader2 = Task.Factory.StartNew(() =>
{
foreach (Builder item in buildersToLoad.GetConsumingEnumerable())
{
Thread.Sleep(1000);
loadedBuilders.Add(item);
}
}, TaskCreationOptions.LongRunning);
Task.WaitAll(loader1, loader2);
return loadedBuilders.ToList();
}
示例14: EndProcessing
protected override void EndProcessing()
{
SevenZipBase.SetLibraryPath(Utils.SevenZipLibraryPath);
var queue = new BlockingCollection<object>();
var worker = CreateWorker();
worker.Queue = queue;
_thread = StartBackgroundThread(worker);
foreach (var o in queue.GetConsumingEnumerable()) {
var record = o as ProgressRecord;
var errorRecord = o as ErrorRecord;
if (record != null) {
WriteProgress(record);
} else if (errorRecord != null) {
WriteError(errorRecord);
} else if (o is string) {
WriteVerbose((string) o);
} else {
WriteObject(o);
}
}
_thread.Join();
}
示例15: MTATaskScheduler
/// <summary>Initializes a new instance of the MTATaskScheduler class with the specified concurrency level.</summary>
/// <param name="numberOfThreads">The number of threads that should be created and used by this scheduler.</param>
/// <param name="nameFormat">The template name form to use to name threads.</param>
public MTATaskScheduler(int numberOfThreads, string nameFormat)
{
// Validate arguments
if (numberOfThreads < 1) throw new ArgumentOutOfRangeException("numberOfThreads");
// Initialize the tasks collection
tasks = new BlockingCollection<Task>();
// Create the threads to be used by this scheduler
_threads = Enumerable.Range(0, numberOfThreads).Select(i =>
{
var thread = new Thread(() =>
{
// Continually get the next task and try to execute it.
// This will continue until the scheduler is disposed and no more tasks remain.
foreach (var t in tasks.GetConsumingEnumerable())
{
TryExecuteTask(t);
}
})
{
IsBackground = true
};
thread.SetApartmentState(ApartmentState.MTA);
thread.Name = String.Format("{0} - {1}", nameFormat, thread.ManagedThreadId);
return thread;
}).ToList();
// Start all of the threads
_threads.ForEach(t => t.Start());
}