本文整理汇总了C#中ConcurrentBag类的典型用法代码示例。如果您正苦于以下问题:C# ConcurrentBag类的具体用法?C# ConcurrentBag怎么用?C# ConcurrentBag使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
ConcurrentBag类属于命名空间,在下文中一共展示了ConcurrentBag类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetExceptions
public IList<Type> GetExceptions(Assembly assembly, IEnumerable<Type> exceptionsToIgnore)
{
Type typeOfException = typeof(Exception);
ConcurrentBag<Type> types = new ConcurrentBag<Type>();
Parallel.ForEach(
assembly.GetTypes(),
type =>
{
if (exceptionsToIgnore != null && exceptionsToIgnore.Any())
{
if (exceptionsToIgnore.Contains(type))
{
return;
}
}
if (typeOfException.IsAssignableFrom(type))
{
types.Add(type);
}
});
return types.ToList();
}
示例2: TrueCraftGame
public TrueCraftGame(MultiplayerClient client, IPEndPoint endPoint)
{
Window.Title = "TrueCraft";
Content.RootDirectory = "Content";
Graphics = new GraphicsDeviceManager(this);
Graphics.SynchronizeWithVerticalRetrace = false;
Graphics.IsFullScreen = UserSettings.Local.IsFullscreen;
Graphics.PreferredBackBufferWidth = UserSettings.Local.WindowResolution.Width;
Graphics.PreferredBackBufferHeight = UserSettings.Local.WindowResolution.Height;
Client = client;
EndPoint = endPoint;
NextPhysicsUpdate = DateTime.MinValue;
ChunkMeshes = new List<Mesh>();
IncomingChunks = new ConcurrentBag<Mesh>();
PendingMainThreadActions = new ConcurrentBag<Action>();
MouseCaptured = true;
var keyboardComponent = new KeyboardComponent(this);
KeyboardComponent = keyboardComponent;
Components.Add(keyboardComponent);
var mouseComponent = new MouseComponent(this);
MouseComponent = mouseComponent;
Components.Add(mouseComponent);
}
示例3: finish_successfully
public void finish_successfully()
{
var handling = new AsyncHandling(ObjectMother.InvocationContext());
var list = new ConcurrentBag<string>();
var task1 = Task.Factory.StartNew(() => {
Thread.Sleep(100);
list.Add("A");
});
var task2 = Task.Factory.StartNew(() => {
Thread.Sleep(100);
list.Add("B");
});
var task3 = Task.Factory.StartNew(() => {
Thread.Sleep(100);
list.Add("C");
});
handling.Push(task1);
handling.Push(task2);
handling.Push(task3);
handling.WaitForAll();
list.OrderBy(x => x).ShouldHaveTheSameElementsAs("A", "B", "C");
}
示例4: ShouldBeUnique
public void ShouldBeUnique()
{
var generatedIds = new ConcurrentBag<Guid>();
var tasks = new List<Task>();
var i = Count;
while (i-- > 0)
{
tasks.Add(
Task.Factory.StartNew(
() =>
{
for (var j = 0; j < 100; j++)
{
var id = SeqGuid.NewGuid();
generatedIds.Add(id);
}
}));
}
Task.WaitAll(tasks.ToArray());
Assert.That(new HashSet<Guid>(generatedIds).Count, Is.EqualTo(Count * 100));
}
示例5: TestPlan
public TestPlan(string name, int iterationsCount, Action<int> action)
{
Name = name;
IterationsCount = iterationsCount;
Action = action;
Results = new ConcurrentBag<TestResult>();
}
示例6: World
public World()
{
worldTime = new DateTime();
rooms = new List<Room>();
rooms.Add(new Room("The Void", "You are standing in the middle of nothing."));
mobs = new ConcurrentBag<NPC>();
NPC test = new NPC("mob", "A slimy sticky stinky mob", new Stats(50, 100), this);
rooms.First().addNPC(test);
mobs.Add(test);
test = new NPC("bob", "A slimy sticky stinky bob", new Stats(50, 100), this);
rooms.First().addNPC(test);
mobs.Add(test);
test = new NPC("sob", "A slimy sticky stinky sob", new Stats(50, 100), this);
rooms.First().addNPC(test);
mobs.Add(test);
test = new NPC("cob", "A slimy sticky stinky cob", new Stats(50, 100), this);
rooms.First().addNPC(test);
mobs.Add(test);
Merchant merch = new Merchant();
merch.name = "merchant";
merch.description = "a merchant of souls";
merch.world = this;
merch.stats = new Stats(10000, 10000);
Item i = new Item("health", "a potion of restore health", 1, "none", 1);
merch.items.addToInventory(i);
rooms.First().addNPC(merch);
mobs.Add(merch);
rooms.First().addItem(new Item("leggings", "a worn pair of leather leggings", 2, "legs", 2));
}
示例7: TestBasicScenarios
public static void TestBasicScenarios()
{
ConcurrentBag<int> cb = new ConcurrentBag<int>();
Task[] tks = new Task[2];
tks[0] = Task.Run(() =>
{
cb.Add(4);
cb.Add(5);
cb.Add(6);
});
// Consume the items in the bag
tks[1] = Task.Run(() =>
{
int item;
while (!cb.IsEmpty)
{
bool ret = cb.TryTake(out item);
Assert.True(ret);
// loose check
Assert.Contains(item, new[] { 4, 5, 6 });
}
});
Task.WaitAll(tks);
}
示例8: Instance_ThreadSafe
public void Instance_ThreadSafe()
{
using (var gate = new Barrier(5))
{
var result = new ConcurrentBag<AnyConstructorFinder>();
Action test = () =>
{
gate.SignalAndWait(20);
var instance = AnyConstructorFinder.Instance;
Thread.MemoryBarrier();
result.Add(instance);
};
var cycleState = Parallel.For(0, 200,
new ParallelOptions { MaxDegreeOfParallelism = 15 },
x => { test(); })
;
while (!cycleState.IsCompleted)
{
Thread.Sleep(100);
}
Assert.IsTrue(result.All(x => x != null));
Assert.IsTrue(result.Distinct().Count() == 1);
}
}
示例9: GetUnlockedAchievements
protected override IEnumerable<Achievement> GetUnlockedAchievements(StatisAnalysisSession statisAnalysisSession, IEnumerable<Achievement> availableAchievements)
{
var unlockedAchievements = new ConcurrentBag<Achievement>();
var tasks = new Task[availableAchievements.Count()];
var i = 0;
foreach (var uncompletedAchievement in availableAchievements)
{
var a = uncompletedAchievement;
tasks[i++] = Task.Factory.StartNew(() =>
{
/* Technically we create a lot of objects all the time.
* It's possible that these objects could have a lifespan longer than just a session.
* However maintaining state is always a PITA */
var achievement = (StaticAnalysisAchievementBase)Activator.CreateInstance(a.AchievementType);
if (achievement.IsAchievementUnlocked(statisAnalysisSession))
{
a.CodeOrigin = achievement.AchievementCodeOrigin;
a.IsCompleted = true;
unlockedAchievements.Add(a);
}
});
}
Task.WaitAll(tasks);
return unlockedAchievements;
}
示例10: Execute
public IEnumerable<IDocument> Execute(IReadOnlyList<IDocument> inputs, IExecutionContext context)
{
// Get syntax trees (supply path so that XML doc includes can be resolved)
ConcurrentBag<SyntaxTree> syntaxTrees = new ConcurrentBag<SyntaxTree>();
Parallel.ForEach(inputs, input =>
{
using (Stream stream = input.GetStream())
{
SourceText sourceText = SourceText.From(stream);
syntaxTrees.Add(CSharpSyntaxTree.ParseText(sourceText,
path: input.String(Keys.SourceFilePath, string.Empty)));
}
});
// Create the compilation (have to supply an XmlReferenceResolver to handle include XML doc comments)
MetadataReference mscorlib = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);
CSharpCompilation compilation = CSharpCompilation
.Create("CodeAnalysisModule", syntaxTrees)
.WithReferences(mscorlib)
.WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary,
xmlReferenceResolver: new XmlFileResolver(context.InputFolder)));
// Get and return the document tree
AnalyzeSymbolVisitor visitor = new AnalyzeSymbolVisitor(context, _symbolPredicate,
_writePath ?? (x => DefaultWritePath(x, _writePathPrefix)), _cssClasses, _docsForImplicitSymbols);
visitor.Visit(compilation.Assembly.GlobalNamespace);
return visitor.Finish();
}
示例11: GetFixAsync
public virtual async Task<CodeAction> GetFixAsync(
ImmutableDictionary<Document, ImmutableArray<Diagnostic>> documentsAndDiagnosticsToFixMap,
FixAllContext fixAllContext)
{
if (documentsAndDiagnosticsToFixMap != null && documentsAndDiagnosticsToFixMap.Any())
{
FixAllLogger.LogDiagnosticsStats(documentsAndDiagnosticsToFixMap);
var fixesBag = new ConcurrentBag<CodeAction>();
using (Logger.LogBlock(FunctionId.CodeFixes_FixAllOccurrencesComputation_Fixes, fixAllContext.CancellationToken))
{
fixAllContext.CancellationToken.ThrowIfCancellationRequested();
var documents = documentsAndDiagnosticsToFixMap.Keys.ToImmutableArray();
var options = new ParallelOptions() { CancellationToken = fixAllContext.CancellationToken };
Parallel.ForEach(documents, options, document =>
{
fixAllContext.CancellationToken.ThrowIfCancellationRequested();
AddDocumentFixesAsync(document, documentsAndDiagnosticsToFixMap[document], fixesBag.Add, fixAllContext).Wait(fixAllContext.CancellationToken);
});
}
if (fixesBag.Any())
{
using (Logger.LogBlock(FunctionId.CodeFixes_FixAllOccurrencesComputation_Merge, fixAllContext.CancellationToken))
{
FixAllLogger.LogFixesToMergeStats(fixesBag);
return await TryGetMergedFixAsync(fixesBag, fixAllContext).ConfigureAwait(false);
}
}
}
return null;
}
示例12: BufferPool
/// <summary>
/// Creates a buffer pool.
/// </summary>
/// <param name="bufferSize">The size, in bytes, of each buffer.</param>
/// <param name="maxBuffers">The maximum number of buffers to keep around, unused; by default, the number of unused buffers is unbounded.</param>
/// <param name="preallocationSize">Initial number of buffers to allocate.</param>
/// <param name="name">Name of the buffer pool.</param>
private BufferPool(int bufferSize, int maxBuffers, int preallocationSize, string name)
{
Name = name;
byteBufferSize = bufferSize;
maxBuffersCount = maxBuffers;
limitBuffersCount = maxBuffers > 0;
buffers = new ConcurrentBag<byte[]>();
var globalPoolSizeStat = IntValueStatistic.FindOrCreate(StatisticNames.SERIALIZATION_BUFFERPOOL_BUFFERS_INPOOL,
() => Count);
allocatedBufferCounter = CounterStatistic.FindOrCreate(StatisticNames.SERIALIZATION_BUFFERPOOL_ALLOCATED_BUFFERS);
checkedOutBufferCounter = CounterStatistic.FindOrCreate(StatisticNames.SERIALIZATION_BUFFERPOOL_CHECKED_OUT_BUFFERS);
checkedInBufferCounter = CounterStatistic.FindOrCreate(StatisticNames.SERIALIZATION_BUFFERPOOL_CHECKED_IN_BUFFERS);
droppedBufferCounter = CounterStatistic.FindOrCreate(StatisticNames.SERIALIZATION_BUFFERPOOL_DROPPED_BUFFERS);
droppedTooLargeBufferCounter = CounterStatistic.FindOrCreate(StatisticNames.SERIALIZATION_BUFFERPOOL_DROPPED_TOO_LARGE_BUFFERS);
// Those 2 counters should be equal. If not, it means we don't release all buffers.
IntValueStatistic.FindOrCreate(StatisticNames.SERIALIZATION_BUFFERPOOL_INUSE_CHECKED_OUT_NOT_CHECKED_IN_BUFFERS,
() => checkedOutBufferCounter.GetCurrentValue()
- checkedInBufferCounter.GetCurrentValue()
- droppedBufferCounter.GetCurrentValue());
IntValueStatistic.FindOrCreate(StatisticNames.SERIALIZATION_BUFFERPOOL_INUSE_ALLOCATED_NOT_INPOOL_BUFFERS,
() => allocatedBufferCounter.GetCurrentValue()
- globalPoolSizeStat.GetCurrentValue()
- droppedBufferCounter.GetCurrentValue());
if (preallocationSize <= 0) return;
var dummy = GetMultiBuffer(preallocationSize * Size);
Release(dummy);
}
示例13: RabbitConnection
public RabbitConnection(ILog log, int maxModels, IConnection connection)
{
_connection = connection;
_log = log;
_asyncLock = new AsyncLock(maxModels);
_models = new ConcurrentBag<IModel>(Enumerable.Range(0, maxModels).Select(_ => connection.CreateModel()));
}
示例14: Main
static void Main(string[] args)
{
ConcurrentBag<int> bag = new ConcurrentBag<int>();
bag.Add(42);
bag.Add(21);
int result;
if (bag.TryTake(out result))
{
Console.WriteLine(result);
}
if (bag.TryPeek(out result))
{
Console.WriteLine("There is a next item: {0}", result);
}
if (bag.TryTake(out result))
{
Console.WriteLine(result);
}
Console.Write("Press a key to exit");
Console.ReadKey();
}
示例15: FirstNews
public IEnumerable<INews> FirstNews()
{
var newsInstance = InterNewsBL.Instance;
var newsList = new ConcurrentBag<INews>();
try
{
var result = newsInstance.SelectTopNews();
result.AsParallel().AsOrdered().ForAll(val =>
{
newsList.Add(new News
{
NewsID = val.NewsID,
DisplayOrder = val.DisplayOrder,
Heading = val.Heading,
ImageUrl = val.ImageUrl,
ShortDesc = val.ShortDescription,
IsRss = val.IsRss,
//NewsDesc= val.NewsDescription,
DttmCreated = val.DttmCreated
});
});
}
catch (Exception)
{
throw;
}
finally
{
newsInstance.Dispose();
}
return newsList.OrderByDescending(v => v.DttmCreated);
}