本文整理汇总了C#中ConcurrentBag.ToArray方法的典型用法代码示例。如果您正苦于以下问题:C# ConcurrentBag.ToArray方法的具体用法?C# ConcurrentBag.ToArray怎么用?C# ConcurrentBag.ToArray使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ConcurrentBag
的用法示例。
在下文中一共展示了ConcurrentBag.ToArray方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Test
public override void Test()
{
var tasks = new ConcurrentBag<Task>();
var tasks2 = new ConcurrentBag<Task>();
//divide by 4 = 64
for (var x = 0; x < 4; x++)
{
int x1 = x;
tasks.Add(
Task.Run(() =>
{
for (var i = (x1 * 64); i <= ((x1 * 64) + 64); i++)
{
int i1 = i;
tasks2.Add(
Task.Run(() =>
{
Items.TryAdd((i1), ConnectTAP(Ip + (i1), 80));
}));
}
}));
}
Task.WaitAll(tasks.ToArray());
Task.WaitAll(tasks2.ToArray());
}
示例2: SimpleBenchmark
static async Task SimpleBenchmark(IFooService fooService)
{
var nCalls = 100 * 1000;
var random = new Random();
var tasksToWait = new ConcurrentBag<Task>();
var sw = Stopwatch.StartNew();
Parallel.For(0, nCalls, i =>
{
//gets a foo with id between 1 and 10, asynchronously
tasksToWait.Add(
fooService.GetFooAsync(random.Next(1, 11)));
});
await Task.WhenAll(tasksToWait.ToArray());
sw.Stop();
Console.WriteLine("{0} calls completed in {1}", nCalls, sw.Elapsed);
Console.WriteLine("Avg time per call: {0} ms", (double)sw.ElapsedMilliseconds / nCalls);
Console.WriteLine("Requests per second: {0}", (double)nCalls / sw.Elapsed.TotalSeconds);
}
示例3: LoadDataParallel
private static Trial[] LoadDataParallel(string path)
{
BlockingCollection<string> inputLines = new BlockingCollection<string>();
ConcurrentBag<Trial> trials = new ConcurrentBag<Trial>();
int itemsAdded = 0;
int itemsProcessed = 0;
const int outputFrequency = 100000;
List<Task> consumerTasks = new List<Task>();
int counter = 0;
using (StreamReader file = new StreamReader(path))
{
// Skip header
file.ReadLine();
string lineRead;
while ((lineRead = file.ReadLine()) != null)
{
inputLines.Add(lineRead);
++itemsAdded;
if (++counter >= outputFrequency)
{
counter = 0;
Console.Out.WriteLine("Trial lines Read: {0}", itemsAdded);
if (inputLines.Count >= outputFrequency * consumerTasks.Count)
{
consumerTasks.Add(Task.Run(() =>
{
string line;
do
{
while (inputLines.TryTake(out line))
{
string[] fields = line.Trim().Split(new char[] { ',' });
if (fields.Length >= 11)
{
Trial trial = new Trial(fields);
trials.Add(trial);
}
int numProcessed = Interlocked.Increment(ref itemsProcessed);
if (numProcessed % 100000 == 0)
Console.Out.WriteLine("Trial lines processed: {0}", numProcessed);
}
Thread.Sleep(100);
} while (!inputLines.IsCompleted);
}));
}
}
}
inputLines.CompleteAdding();
}
Task.WaitAll(consumerTasks.ToArray());
return trials.ToArray();
}
示例4: Invokes_Only_One_Action_At_A_Time
public void Invokes_Only_One_Action_At_A_Time()
{
var it = new InvocationThrottle(min: TimeSpan.FromMilliseconds(1), max: TimeSpan.FromMilliseconds(2));
int im_doing_stuff = 0;
bool hasException = false;
int invocation_count = 0;
ConcurrentBag<AutoResetEvent> ares = new ConcurrentBag<AutoResetEvent>();
// invoke action in a look
for (int i = 0; i < 10; i++)
{
var local_i = i;
// some actions will be cancelled bevause min time has not passed
// those should never even start running
// there always should be at most one action running at a tim
it.InvokeAsync(() =>
{
var are = new AutoResetEvent(initialState: false);
ares.Add(are);
try
{
Interlocked.Increment(ref invocation_count);
LongAction(ref im_doing_stuff);
// given min of 1s, this should be invoked only once
if(local_i < 9 && invocation_count != 1)
{
throw new Exception();
}
}
catch(Exception ex)
{
hasException = true;
}
are.Set();
});
Thread.Sleep(1);
}
Thread.Sleep(200);
OnMtaThread(() => AutoResetEvent.WaitAll(ares.ToArray()));
if (hasException)
Assert.Fail();
}
示例5: RemoveInvalidFileTypesInParallel
public static string[] RemoveInvalidFileTypesInParallel(string[] files)
{
var validFiles = new ConcurrentBag<string>();
Parallel.ForEach(files, async file =>
{
if (await IsValidImageAsync(file))
validFiles.Add(file);
});
return validFiles.ToArray();
}
示例6: Build
public UiArchives Build()
{
string[] lists = Directory.GetFiles(_gameLocation.SystemDirectory, "filelist*.bin");
ConcurrentBag<UiArchiveNode> nodes = new ConcurrentBag<UiArchiveNode>();
Parallel.ForEach(lists, fileName =>
{
ArchiveAccessor accessor = new ArchiveAccessor(GetBinaryFilePath(fileName), fileName);
nodes.Add(new UiArchiveNode(accessor, null));
});
return new UiArchives(nodes.ToArray());
}
示例7: InvokesOnlyOneAtTheTimeAndLastOneWins
public void InvokesOnlyOneAtTheTimeAndLastOneWins()
{
var it = new InvocationThrottle(min: TimeSpan.FromMilliseconds(1), max: TimeSpan.FromMilliseconds(2));
int im_doing_stuff = 0;
bool hasException = false;
int invocation_count = 0;
ConcurrentBag<AutoResetEvent> ares = new ConcurrentBag<AutoResetEvent>();
for (int i = 0; i < 10; i++)
{
var local_i = i;
it.Invoke(() =>
{
var are = new AutoResetEvent(initialState: false);
ares.Add(are);
try
{
Interlocked.Increment(ref invocation_count);
LongAction(ref im_doing_stuff);
if((local_i < 9 && invocation_count != 1) || (local_i == 9 && invocation_count != 2))
{
throw new Exception();
}
}
catch(Exception ex)
{
hasException = true;
}
are.Set();
});
Thread.Sleep(1);
}
Thread.Sleep(200);
OnMtaThread(() => AutoResetEvent.WaitAll(ares.ToArray()));
if (hasException)
Assert.Fail();
}
示例8: ChangePropertyTest
public void ChangePropertyTest()
{
var firedPropertyChangedEventArgs
= new ConcurrentBag<PropertyChangedEventArgs>();
var node = new Node();
Assert.That(node, Is.Not.Null);
node.PropertyChanged += (sender, args) => { firedPropertyChangedEventArgs.Add(args); };
node.X = 5;
var array = firedPropertyChangedEventArgs.ToArray();
Assert.That(firedPropertyChangedEventArgs.Count, Is.EqualTo(1));
Assert.That(array[0].PropertyName, Is.EqualTo("X"));
}
示例9: Test
public override void Test()
{
var tasks = new ConcurrentBag<Task>();
for (var i = 0; i <= 255; i++)
{
int i1 = i;
tasks.Add(
Task.Run(() =>
{
Items.TryAdd(i1, ConnectAPM(Ip + i1, 80));
}));
}
Task.WaitAll(tasks.ToArray());
}
示例10: CandExecuteReceiving
public void CandExecuteReceiving()
{
const int Value = 1;
var list = new List<int>();
using (var helper = new SendReceiveLockHelper(FullName, EmptyName))
{
helper.AddSendAction(() => list.Add(Value));
helper.Send(TimeSpan.FromMilliseconds(1000)).Should().BeTrue();
helper.AddReceiveFunction(() => list[0]);
var result = new ConcurrentBag<int>();
helper.Receive<int>(result, TimeSpan.FromMilliseconds(1000)).Should().BeTrue();
result.Count.Should().Be(1);
result.ToArray()[0].Should().Be(Value);
}
}
示例11: ShouldWork
public async Task ShouldWork()
{
var client = NewAsyncClient();
var tasks = new ConcurrentBag<Task>();
// upload 10 files with the same content but different names concurrently
Assert.DoesNotThrow(
() =>
Parallel.For(0, 10, x => tasks.Add(client.UploadAsync("test" + x, new MemoryStream(new byte[] {1, 2, 3, 4, 5})))));
Task.WaitAll(tasks.ToArray());
var hash = new MemoryStream(new byte[] {1, 2, 3, 4, 5}).GetMD5Hash();
for (var i = 0; i < 10; i++)
{
var uploadedContent = await client.DownloadAsync("test" + i);
Assert.Equal(hash, uploadedContent.GetMD5Hash());
}
}
示例12: Execute
public ITaskResult<IdentityWithResult[]> Execute(Layer layer, Func<Identity, TaskContext> contextFactory, ITaskInterceptor interceptor)
{
ITaskResult<IdentityWithResult[]> failure = null;
var results = new ConcurrentBag<IdentityWithResult>();
var layerTasks = layer.Items.Select(item => SystemTask.Factory.StartNew(() =>
{
Identity id = item.Id;
TaskContext taskContext = contextFactory(id);
if (interceptor != null)
{
interceptor.BeforeTaskExecute(id, item.Task, taskContext);
}
ITaskResult<object> result = item.Task.Execute(taskContext);
if (interceptor != null)
{
interceptor.AfterTaskExecute(id, item.Task, taskContext, result);
}
if (result.IsSuccess)
{
results.Add(new IdentityWithResult(id, result.Data));
}
else
{
failure = new FailureResult<IdentityWithResult[]>(result.Error);
}
})).ToArray();
SystemTask.WaitAll(layerTasks);
if (failure != null)
{
return failure;
}
return new SuccessResult<IdentityWithResult[]>(results.ToArray());
}
示例13: TwoThreads
public void TwoThreads()
{
int count1 = 0;
int count2 = 0;
var allTasks = new ConcurrentBag<Task>();
using (var poller = new NetMQPoller())
{
poller.RunAsync();
Task t1 = Task.Factory.StartNew(() =>
{
for (int i = 0; i < 100; i++)
{
var task = new Task(() => { count1++; });
allTasks.Add(task);
task.Start(poller);
}
});
Task t2 = Task.Factory.StartNew(() =>
{
for (int i = 0; i < 100; i++)
{
var task = new Task(() => { count2++; });
allTasks.Add(task);
task.Start(poller);
}
});
t1.Wait(1000);
t2.Wait(1000);
Task.WaitAll(allTasks.ToArray(), 1000);
Assert.AreEqual(100, count1);
Assert.AreEqual(100, count2);
}
}
示例14: FormatTableLoadException
/// <summary>
/// This constructor takes a collection of errors occurred during construction
/// time.
/// </summary>
/// <param name="loadErrors">
/// The errors that occured
/// </param>
internal FormatTableLoadException(ConcurrentBag<string> loadErrors) :
base(StringUtil.Format(FormatAndOutXmlLoadingStrings.FormatTableLoadErrors))
{
_errors = new Collection<string>(loadErrors.ToArray());
SetDefaultErrorRecord();
}
示例15: Execute
public Query Execute(Query q)
{
if (!q.ResponsibleNodesAssigned) {
var responsibleNodes = AssignResponsibleNodes(q);
var resultQList = new ConcurrentBag<Query>();
Parallel.ForEach(responsibleNodes, delegate (IOverlayNode node) {
var channel = CommunicationMgr.GetChannel(node);
resultQList.Add(channel.Service.Execute(q));
});
if (OverlayParams.StatisticsEnabled) {
// add hops for query execution itself
q.AggregateStatistics(resultQList.ToArray());
q.StatsCollector.IncreaseHopsCount(responsibleNodes.Distinct().Count());
}
return MergeQueryResults(resultQList, q);
} else {
q = SetQueryResult(q);
return q;
}
}