本文整理汇总了C#中BlockingCollection类的典型用法代码示例。如果您正苦于以下问题:C# BlockingCollection类的具体用法?C# BlockingCollection怎么用?C# BlockingCollection使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
BlockingCollection类属于命名空间,在下文中一共展示了BlockingCollection类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: AsynchronousTraceListenerWrapper
/// <summary>
/// Initializes a new instance of the <see cref="AsynchronousTraceListenerWrapper" /> class.
/// </summary>
/// <param name="wrappedTraceListener">The wrapped trace listener.</param>
/// <param name="ownsWrappedTraceListener">Indicates whether the wrapper should dispose the wrapped trace listener.</param>
/// <param name="bufferSize">Size of the buffer for asynchronous requests.</param>
/// <param name="maxDegreeOfParallelism">The max degree of parallelism for thread safe listeners. Specify <see langword="null"/> to use the current core count.</param>
/// <param name="disposeTimeout">The timeout for waiting to complete buffered requests when disposing. When <see langword="null" /> the default of <see cref="Timeout.InfiniteTimeSpan" /> is used.</param>
public AsynchronousTraceListenerWrapper(
TraceListener wrappedTraceListener,
bool ownsWrappedTraceListener = true,
int? bufferSize = DefaultBufferSize,
int? maxDegreeOfParallelism = null,
TimeSpan? disposeTimeout = null)
{
Guard.ArgumentNotNull(wrappedTraceListener, "wrappedTraceListener");
CheckBufferSize(bufferSize);
CheckMaxDegreeOfParallelism(maxDegreeOfParallelism);
CheckDisposeTimeout(disposeTimeout);
this.wrappedTraceListener = wrappedTraceListener;
this.ownsWrappedTraceListener = ownsWrappedTraceListener;
this.disposeTimeout = disposeTimeout ?? Timeout.InfiniteTimeSpan;
this.closeSource = new CancellationTokenSource();
this.requests = bufferSize != null ? new BlockingCollection<Action<TraceListener>>(bufferSize.Value) : new BlockingCollection<Action<TraceListener>>();
if (this.wrappedTraceListener.IsThreadSafe)
{
this.maxDegreeOfParallelism = maxDegreeOfParallelism.HasValue ? maxDegreeOfParallelism.Value : Environment.ProcessorCount;
this.asyncProcessingTask = Task.Factory.StartNew(this.ProcessRequestsInParallel, CancellationToken.None, TaskCreationOptions.HideScheduler | TaskCreationOptions.LongRunning, TaskScheduler.Default);
}
else
{
this.asyncProcessingTask = Task.Factory.StartNew(this.ProcessRequests, CancellationToken.None, TaskCreationOptions.HideScheduler | TaskCreationOptions.LongRunning, TaskScheduler.Default);
}
}
示例2: 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, Action<IEnumerable<Result>> fireNewCommand)
{
var data = new Dictionary<JointType, InputVector>();
foreach (var skeleton in input.GetConsumingEnumerable())
{
foreach (var joint in skeleton.Joints)
{
if (!data.ContainsKey(joint.JointType))
{
data.Add(joint.JointType, new InputVector());
}
data[joint.JointType].Stream.Add(joint.Point);
}
if (data.First().Value.Stream.Count < 5)
{
continue;
}
var results = Recognizer.Recognize(data);
try
{
fireNewCommand(results);
}
catch (Exception)
{
if (data.First().Value.Stream.Count > 40)
{
data.Clear();
}
continue;
}
data.Clear();
}
}
示例3: CommandProcessor
public CommandProcessor(BlockingCollection<Job> allJobs, Scheduler scheduler, JobQueue jobQueue, QueueProcessor queueProcessor)
{
_allJobs = allJobs;
_scheduler = scheduler;
_jobQueue = jobQueue;
_queueProcessor = queueProcessor;
}
示例4: VideoClass
public VideoClass(string url, string languageCode)
{
Url = url;
Subtitles = new BlockingCollection<SubtitlesClass>();
Language = TEDdownloader.Language.GetLanguage(languageCode);
LanguageCode = languageCode;
}
示例5: Main
static void Main(string[] args)
{
Console.WriteLine("=== In Line Execution ===");
Task<string>[] tasks = GetTasks();
string[] all = Task.WhenAll(tasks).Result;
Console.WriteLine(string.Join("", all));
Console.WriteLine("=== Standard Live Execution ===");
tasks = GetTasks();
BlockingCollection<string> results = new BlockingCollection<string>();
Task.WaitAll(tasks.Select(async t =>
{
results.Add(await t);
Console.WriteLine("[{0:hh:mm:ss.fff}] Current result: [{1}]", DateTime.Now, string.Join("", results));
}).ToArray());
Console.WriteLine("=== Pragmateek Live Execution ===");
results = new BlockingCollection<string>();
tasks = GetTasks();
Task.WaitAll(tasks.Select(t => t.ContinueWith(p =>
{
results.Add(p.Result);
Console.WriteLine("[{0:hh:mm:ss.fff}] Current result: [{1}]", DateTime.Now, string.Join("", results));
})).ToArray());
}
示例6: TestWritableTransportServer
public void TestWritableTransportServer()
{
BlockingCollection<WritableString> queue = new BlockingCollection<WritableString>();
List<string> events = new List<string>();
IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, 0);
var remoteHandler = Observer.Create<TransportEvent<WritableString>>(tEvent => queue.Add(tEvent.Data));
using (var server = new WritableTransportServer<WritableString>(endpoint, remoteHandler, _tcpPortProvider, _injector))
{
server.Run();
IPEndPoint remoteEndpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), server.LocalEndpoint.Port);
using (var client = new WritableTransportClient<WritableString>(remoteEndpoint, _injector))
{
client.Send(new WritableString("Hello"));
client.Send(new WritableString(", "));
client.Send(new WritableString("World!"));
events.Add(queue.Take().Data);
events.Add(queue.Take().Data);
events.Add(queue.Take().Data);
}
}
Assert.AreEqual(3, events.Count);
Assert.AreEqual(events[0], "Hello");
Assert.AreEqual(events[1], ", ");
Assert.AreEqual(events[2], "World!");
}
示例7: BlockingCollectionQueue
public BlockingCollectionQueue()
{
_writerQueue = new BlockingCollection<User>();
_readerQueue = new BlockingCollection<User>();
_currentQueue = _writerQueue;
Task.Factory.StartNew(() => ConsumerFunc(), TaskCreationOptions.None);
}
示例8: HardDiskCache
public HardDiskCache(string cachePath)
{
CachePath = cachePath;
indexList = new List<LocationInfo>();
imageQueue = new BlockingCollection<Image>();
StartConsumerThread();
}
示例9: GetLogQueue
public static BlockingCollection<LogMsg> GetLogQueue()
{
if (m_logQueue == null) {
m_logQueue = new BlockingCollection<LogMsg> ();
}
return m_logQueue;
}
示例10: TestStreamingOneWayCommunication
public void TestStreamingOneWayCommunication()
{
IPAddress listeningAddress = IPAddress.Parse("127.0.0.1");
BlockingCollection<string> queue = new BlockingCollection<string>();
List<string> events = new List<string>();
IStreamingCodec<string> codec = TangFactory.GetTang().NewInjector().GetInstance<StringStreamingCodec>();
using (var remoteManager1 = _remoteManagerFactory1.GetInstance<string>(listeningAddress, codec))
using (var remoteManager2 = _remoteManagerFactory1.GetInstance<string>(listeningAddress, codec))
{
var observer = Observer.Create<string>(queue.Add);
IPEndPoint endpoint1 = new IPEndPoint(listeningAddress, 0);
remoteManager2.RegisterObserver(endpoint1, observer);
var remoteObserver = remoteManager1.GetRemoteObserver(remoteManager2.LocalEndpoint);
remoteObserver.OnNext("abc");
remoteObserver.OnNext("def");
remoteObserver.OnNext("ghi");
events.Add(queue.Take());
events.Add(queue.Take());
events.Add(queue.Take());
}
Assert.AreEqual(3, events.Count);
}
示例11: CanGetNotificationAboutDocumentPut
public void CanGetNotificationAboutDocumentPut()
{
using(GetNewServer())
{using (var store = new DocumentStore
{
Url = "http://localhost:8079",
Conventions =
{
FailoverBehavior = FailoverBehavior.FailImmediately
}
}.Initialize())
{
var list = new BlockingCollection<DocumentChangeNotification>();
var taskObservable = store.Changes();
taskObservable.Task.Wait();
var observableWithTask = taskObservable.ForDocument("items/1");
observableWithTask.Task.Wait();
observableWithTask.Subscribe(list.Add);
using (var session = store.OpenSession())
{
session.Store(new Item(), "items/1");
session.SaveChanges();
}
DocumentChangeNotification documentChangeNotification;
Assert.True(list.TryTake(out documentChangeNotification, TimeSpan.FromSeconds(3)));
Assert.Equal("items/1", documentChangeNotification.Id);
Assert.Equal(documentChangeNotification.Type, DocumentChangeTypes.Put);
Assert.NotNull(documentChangeNotification.Etag);
}
Thread.Sleep(1000);
}
}
示例12: OutBuffer
public OutBuffer(int maxSizeAsPowerOfTwo)
{
//_completeds = new BlockingCollection<TaskCompleted>((int)Math.Pow(2, maxSizeAsPowerOfTwo));
//This is for output, and not spcifying the size revert to ConcurrentQueue.
//Bounding slows down considerably. Should remove when ring array in place.
_completeds = new BlockingCollection<TaskCompleted>();
}
示例13: TestOneWayCommunicationClientOnly
public void TestOneWayCommunicationClientOnly()
{
IPAddress listeningAddress = IPAddress.Parse("127.0.0.1");
BlockingCollection<string> queue = new BlockingCollection<string>();
List<string> events = new List<string>();
using (var remoteManager1 = _remoteManagerFactory.GetInstance(new StringCodec()))
using (var remoteManager2 = _remoteManagerFactory.GetInstance(listeningAddress, new StringCodec()))
{
IPEndPoint remoteEndpoint = new IPEndPoint(listeningAddress, 0);
var observer = Observer.Create<string>(queue.Add);
remoteManager2.RegisterObserver(remoteEndpoint, observer);
var remoteObserver = remoteManager1.GetRemoteObserver(remoteManager2.LocalEndpoint);
remoteObserver.OnNext("abc");
remoteObserver.OnNext("def");
remoteObserver.OnNext("ghi");
events.Add(queue.Take());
events.Add(queue.Take());
events.Add(queue.Take());
}
Assert.Equal(3, events.Count);
}
示例14: DefaultActionExecutionService
/// <summary>Parameterized constructor.
/// </summary>
/// <param name="loggerFactory"></param>
public DefaultActionExecutionService(ILoggerFactory loggerFactory)
{
_logger = loggerFactory.Create(GetType().Name);
_actionQueue = new BlockingCollection<ActionInfo>(new ConcurrentQueue<ActionInfo>());
_worker = new Worker(TryTakeAndExecuteAction, DefaultPeriod);
_worker.Start();
}
示例15: Reducer
/// <summary>
/// Constructor
/// </summary>
public Reducer()
{
_distinctWordList = new ConcurrentDictionary<string, int>();
var concurrentBag = new ConcurrentBag<string>();
_wordChunks = new BlockingCollection<string>(concurrentBag);
Numwords = 0;
}