本文整理汇总了C#中ConcurrentBag.Any方法的典型用法代码示例。如果您正苦于以下问题:C# ConcurrentBag.Any方法的具体用法?C# ConcurrentBag.Any怎么用?C# ConcurrentBag.Any使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ConcurrentBag
的用法示例。
在下文中一共展示了ConcurrentBag.Any方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: 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;
var tasks = documents.Select(d => AddDocumentFixesAsync(d, documentsAndDiagnosticsToFixMap[d], fixesBag.Add, fixAllContext))
.ToArray();
await Task.WhenAll(tasks).ConfigureAwait(false);
}
if (fixesBag.Any())
{
using (Logger.LogBlock(FunctionId.CodeFixes_FixAllOccurrencesComputation_Merge, fixAllContext.CancellationToken))
{
FixAllLogger.LogFixesToMergeStats(fixesBag);
return await TryGetMergedFixAsync(fixesBag, fixAllContext).ConfigureAwait(false);
}
}
}
return null;
}
示例2: 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;
}
示例3: Notify
public override void Notify(ConcurrentBag<AMQPQueueMetric> busyQueues,
ConcurrentBag<AMQPQueueMetric> quietQueues) {
if (busyQueues.Any()) {
if (!amqpAdapter.IsConnected)
amqpAdapter.Connect();
Parallel.ForEach(busyQueues, amqpQueueMetric => amqpAdapter.Publish(ScaleMessage.Create(ScaleDirective.Out),
exchangeName, amqpQueueMetric.QueueName));
}
if (!quietQueues.Any()) return;
if (!amqpAdapter.IsConnected)
amqpAdapter.Connect();
Parallel.ForEach(quietQueues.Where(q => !q.AMQPQueueMetricAnalysisResult.Equals(AMQPQueueMetricAnalysisResult.Stable)), amqpQueueMetric => amqpAdapter.Publish(ScaleMessage.Create(ScaleDirective.In),
exchangeName, amqpQueueMetric.QueueName));
}
示例4: GenerateAssemblyReferenceGraph
public BidirectionalGraph<AssemblyVertex, EquatableEdge<AssemblyVertex>> GenerateAssemblyReferenceGraph(IEnumerable<Regex> exclusions, ConcurrentBag<string> files, bool verbose)
{
if (verbose) Console.WriteLine("Processing {0} files.", files.Count);
var edges = new ConcurrentBag<EquatableEdge<AssemblyVertex>>();
var current = 0;
var total = files.Count;
Parallel.ForEach(files, file =>
{
if (verbose) Console.Write("\rProcessing file: {0} of {1}", ++current, total);
AssemblyDefinition assembly;
try
{
assembly = AssemblyDefinition.ReadAssembly(new MemoryStream(_fileSystem.File.ReadAllBytes(file)));
}
catch (Exception)
{
if (verbose) Console.WriteLine("Skipping file as it does not appear to be a .Net assembly: {0}", file);
return;
}
foreach (var reference in assembly.MainModule.AssemblyReferences)
{
var exists = files.Any(f =>
{
var fileInfo = new FileInfo(f);
return reference.Name.Equals(fileInfo.Name.Replace(fileInfo.Extension, ""), StringComparison.OrdinalIgnoreCase);
});
if (!exists)
{
string assemblyPath;
exists = _gacResolver.AssemblyExists(reference.FullName, out assemblyPath);
}
var assemblyName = new AssemblyName(assembly.FullName);
edges.Add(CreateNewEdge(reference, exists, assemblyName, exclusions));
}
});
if (verbose) Console.WriteLine();
if (verbose) Console.WriteLine("Creating Graph...");
var graph = new BidirectionalGraph<AssemblyVertex, EquatableEdge<AssemblyVertex>>();
var allVertices = edges.Select(e => e.Source).Concat(edges.Select(e => e.Target));
var distinctVertices = allVertices.Distinct();
graph.AddVertexRange(distinctVertices);
graph.AddEdgeRange(edges);
return graph;
}
示例5: ListContacts
public override async Task ListContacts(ContactQuery query)
{
ContactLite[] returnUsers = null;
Task.Run(async () =>
{
var bExceptionRaised = false;
try
{
var finallist = new ConcurrentBag<ContactLite>();
var agenda = await ContactManager.RequestStoreAsync();
var foundContactList = await agenda.FindContactsAsync();
if (query != null)
{
WindowsPhoneUtils.Log("Listing contacts by query: " + query);
FilterReturnedContacts(foundContactList, finallist, query);
}
else
{
WindowsPhoneUtils.Log("Listing ALL contacts...");
foundContactList.AsParallel()
.ForAll(contact => finallist.Add(new ContactLite
{
ID = contact.Id.Replace("{", "").Replace(".", "").Replace("}", ""),
DisplayName = contact.DisplayName,
Name = contact.FirstName,
Firstname = contact.MiddleName,
Lastname = contact.LastName,
Phones = GetContactPhonesArray(contact),
Emails = GetContactEmailArray(contact)
}));
}
returnUsers = finallist.ToArray();
}
catch (UnauthorizedAccessException ex)
{
WindowsPhoneUtils.Log("Not enough privileges to access Contacts");
WindowsPhoneUtils.InvokeCallback(AccessDeniedContactsCallback, WindowsPhoneUtils.CALLBACKID, null);
return;
}
catch (Exception ex)
{
//error
bExceptionRaised = true;
}
if (bExceptionRaised)
{
try
{
_faultyLetters = new ConcurrentBag<string>();
_startingLetters = new ConcurrentBag<string>();
_finalUsers.Clear();
await StartContactSeach(String.Empty, query);
returnUsers = _finalUsers.Values.ToArray();
_startingLetters.AsParallel().ForAll(startingLetter =>
{
if (!_faultyLetters.Any(
faultySilabe =>
faultySilabe.StartsWith(startingLetter,
StringComparison.CurrentCultureIgnoreCase)))
_faultyLetters.Add(startingLetter);
});
WindowsPhoneUtils.InvokeCallback(WpContactsFailedCallback, WindowsPhoneUtils.CALLBACKID, JsonConvert.SerializeObject(_faultyLetters.OrderBy(x => x).ToArray()));
}
catch (Exception ex)
{
//UNHANDLED ERROR
WindowsPhoneUtils.Log("Unhandled error recovering contacts:" + ex.Message);
}
}
WindowsPhoneUtils.InvokeCallback(ListContactsCallback, WindowsPhoneUtils.CALLBACKID, JsonConvert.SerializeObject(returnUsers));
});
}
示例6: GetColonnesCard
public async Task<List<ColonneCard>> GetColonnesCard()
{
return await Task.Run(() =>
{
using (var db = new StationContext())
{
var cardList = new ConcurrentBag<ColonneCard>();
var nd = new ColonneCard("");
if (nd.Pompes.Any())
cardList.Add(nd);
var cols = (db.Pompes.Where(s => !s.IsDeleted).ToList()
.Where(s => !string.IsNullOrEmpty(s.Colonne))
.Select(s => s.Colonne.ToLower())).Distinct().ToList();
Parallel.ForEach(cols, dep => cardList.Add(new ColonneCard(dep)));
return cardList.Any() ? cardList.OrderBy(d => d.Libel).ToList() : null;
}
});
}
示例7: TestSendReceiveRequestCore
private static void TestSendReceiveRequestCore( IPEndPoint endPoint, int count, int concurrency )
{
_SetUpFixture.EnsureThreadPoolCapacity();
using ( var clientTransportManager = new UdpClientTransportManager( new RpcClientConfiguration() { PreferIPv4 = true } ) )
{
var connectTask = clientTransportManager.ConnectAsync( endPoint );
if ( !connectTask.Wait( Debugger.IsAttached ? Timeout.Infinite : TimeoutMilliseconds ) )
{
throw new TimeoutException();
}
using ( var clientTransport = connectTask.Result )
{
for ( int i = 0; i < count; i++ )
{
using ( var latch = new CountdownEvent( concurrency ) )
{
var ids = Enumerable.Range( i * concurrency, concurrency ).ToArray();
var args = Enumerable.Repeat( 0, concurrency ).Select( _ => Guid.NewGuid().ToString() ).ToArray();
var idAndArgs = ids.Zip( args, ( id, arg ) => new { MessageId = id, Guid = arg.ToString() } );
var requestTable = new ConcurrentDictionary<int, string>();
var responseTable = new ConcurrentDictionary<int, string>();
var exceptions = new ConcurrentBag<Exception>();
if ( !Task.Factory.ContinueWhenAll(
idAndArgs.Select(
idAndArg =>
Task.Factory.StartNew(
() =>
{
var requestContext = clientTransport.GetClientRequestContext();
requestTable[ idAndArg.MessageId ] = idAndArg.Guid;
requestContext.SetRequest(
idAndArg.MessageId,
"Dummy",
( responseContext, exception, completedSynchronously ) =>
{
try
{
if ( exception != null )
{
exceptions.Add( exception );
}
else
{
// Server returns args as array, so store only first element.
responseTable[ responseContext.MessageId.Value ] = Unpacking.UnpackArray( responseContext.ResultBuffer )[ 0 ].AsString();
}
}
finally
{
latch.Signal();
}
}
);
requestContext.ArgumentsPacker.PackArrayHeader( 1 );
requestContext.ArgumentsPacker.Pack( idAndArg.Guid );
return requestContext;
}
)
).ToArray(),
previouses =>
{
var contexts = previouses.Select( previous => previous.Result ).ToArray();
foreach ( var context in contexts )
{
clientTransport.Send( context );
}
}
).ContinueWith(
previous =>
{
if ( previous.IsFaulted )
{
throw previous.Exception;
}
// receive
if ( !latch.Wait( Debugger.IsAttached ? Timeout.Infinite : TimeoutMilliseconds ) )
{
throw new TimeoutException( "Receive" );
}
if ( exceptions.Any() )
{
throw new AggregateException( exceptions );
}
Assert.That( requestTable.Count, Is.EqualTo( concurrency ) );
Assert.That( requestTable, Is.EquivalentTo( responseTable ) );
}
).Wait( Debugger.IsAttached ? Timeout.Infinite : TimeoutMilliseconds ) )
{
throw new TimeoutException();
}
}
}
//.........这里部分代码省略.........
示例8: ExtractStandaloneLibraries
private static void ExtractStandaloneLibraries(string path)
{
var result = CyPhyComponentAuthoring.Modules
.EDAModelImport
.GetDevicesInEagleModel(path);
ConcurrentBag<Tuple<String, Exception>> cb_exceptions = new ConcurrentBag<Tuple<String, Exception>>();
ConcurrentBag<Tuple<String, avm.schematic.SchematicModel>> cb_schematics = new ConcurrentBag<Tuple<string, avm.schematic.SchematicModel>>();
Parallel.ForEach(result, device =>
{
var parts = device.Split('\\');
var lib = parts[0];
var devSet = parts[1];
var dev = parts[2];
try
{
var deviceXML = CyPhyComponentAuthoring.Modules
.EDAModelImport
.GetEagleDevice(path, lib, devSet, dev);
var standaloneXML = CyPhyComponentAuthoring.Modules
.EDAModelImport
.ExtractStandaloneLibrary(deviceXML);
}
catch (Exception e)
{
cb_exceptions.Add(new Tuple<String, Exception>(device, e));
}
});
if (cb_exceptions.Any())
{
String msg = String.Format("Exceptions encountered when extracting libraries for {0} device(s):"
+ Environment.NewLine + Environment.NewLine,
cb_exceptions.Count);
foreach (var tuple in cb_exceptions)
{
msg += String.Format("{0}: {1}" + Environment.NewLine + Environment.NewLine,
tuple.Item1,
tuple.Item2);
}
Assert.True(false, msg);
}
}
示例9: GetFixAsync
internal override async Task<CodeAction> GetFixAsync(
ImmutableDictionary<Project, ImmutableArray<Diagnostic>> projectsAndDiagnosticsToFixMap,
FixAllState fixAllState, CancellationToken cancellationToken)
{
if (projectsAndDiagnosticsToFixMap != null && projectsAndDiagnosticsToFixMap.Any())
{
FixAllLogger.LogDiagnosticsStats(projectsAndDiagnosticsToFixMap);
var fixesBag = new ConcurrentBag<CodeAction>();
using (Logger.LogBlock(FunctionId.CodeFixes_FixAllOccurrencesComputation_Fixes, cancellationToken))
{
var projects = projectsAndDiagnosticsToFixMap.Keys;
var tasks = projects.Select(p => AddProjectFixesAsync(p, projectsAndDiagnosticsToFixMap[p], fixesBag.Add, fixAllState, cancellationToken))
.ToArray();
await Task.WhenAll(tasks).ConfigureAwait(false);
}
if (fixesBag.Any())
{
using (Logger.LogBlock(FunctionId.CodeFixes_FixAllOccurrencesComputation_Merge, cancellationToken))
{
FixAllLogger.LogFixesToMergeStats(fixesBag);
return await TryGetMergedFixAsync(fixesBag, fixAllState, cancellationToken).ConfigureAwait(false);
}
}
}
return null;
}
示例10: TestSendNotifyCore
private static void TestSendNotifyCore( IPEndPoint endPoint, CountdownEvent arrivalLatch, IProducerConsumerCollection<string> arrivedIds, int count )
{
using ( var clientTransportManager = new UdpClientTransportManager( new RpcClientConfiguration() { PreferIPv4 = true } ) )
using ( var connectTask = clientTransportManager.ConnectAsync( endPoint ) )
{
if ( !connectTask.Wait( Debugger.IsAttached ? Timeout.Infinite : TimeoutMilliseconds ) )
{
throw new TimeoutException();
}
using ( var clientTransport = connectTask.Result )
{
for ( int i = 0; i < count; i++ )
{
if ( arrivalLatch != null )
{
arrivalLatch.Reset();
}
var args = Enumerable.Repeat( 0, arrivalLatch.InitialCount ).Select( _ => Guid.NewGuid().ToString() ).ToArray();
var exceptions = new ConcurrentBag<Exception>();
if ( !Task.Factory.ContinueWhenAll(
args.Select(
arg =>
Task.Factory.StartNew(
() =>
{
var requestContext = clientTransport.GetClientRequestContext();
requestContext.SetNotification(
"Dummy",
( exception, completedSynchronously ) =>
{
if ( exception != null )
{
exceptions.Add( exception );
}
arrivalLatch.Signal();
}
);
requestContext.ArgumentsPacker.PackArrayHeader( 1 );
requestContext.ArgumentsPacker.Pack( arg );
return requestContext;
}
)
).ToArray(),
previouses =>
{
var contexts = previouses.Select( previous => previous.Result ).ToArray();
foreach ( var context in contexts )
{
clientTransport.Send( context );
}
}
).ContinueWith(
previous =>
{
if ( previous.IsFaulted )
{
throw previous.Exception;
}
// receive
if ( !arrivalLatch.Wait( Debugger.IsAttached ? Timeout.Infinite : TimeoutMilliseconds ) )
{
throw new TimeoutException( "Receive" );
}
if ( exceptions.Any() )
{
throw new AggregateException( exceptions );
}
}
).Wait( Debugger.IsAttached ? Timeout.Infinite : TimeoutMilliseconds ) )
{
throw new TimeoutException();
}
}
}
}
}
示例11: ConvertTo
/// <summary>
/// Converts some given data into a listing instance.
/// </summary>
/// <param name="data">some data source, like Xml data or json data.</param>
/// <param name="areBadCharactersRemoved">Help clean up the data.</param>
/// <param name="isClearAllIsModified">After the data is loaded, do we clear all IsModified fields so it looks like the listing(s) are all ready to be used and/or compared against other listings.</param>
/// /// <returns>List of listings and any unhandled data.</returns>
public ConvertToResult ConvertTo(string data,
bool areBadCharactersRemoved = false,
bool isClearAllIsModified = false)
{
data.ShouldNotBeNullOrEmpty();
// Remove any BOM if one exists.
// REF: http://stackoverflow.com/questions/5098757/how-to-tell-asciiencoding-class-not-to-decode-the-byte-order-mark
data = RemoveByteOrderMark(data);
var validationErrorMessage = ValidateXmlString(data);
if (!string.IsNullOrWhiteSpace(validationErrorMessage))
{
if (!areBadCharactersRemoved)
{
return new ConvertToResult
{
Errors = new List<ParsedError>
{
new ParsedError(validationErrorMessage, "The entire data source.")}
};
}
// Some bad data occurs, so lets clean any bad data out.
data = RemoveInvalidXmlChars(data);
}
// Now split it up into the known listing types.
SplitElementResult elements;
try
{
elements = SplitReaXmlIntoElements(data);
}
catch (Exception exception)
{
return new ConvertToResult
{
Errors = new List<ParsedError>
{
new ParsedError(exception.Message,
"Failed to parse the provided xml data because it contains some invalid data. Pro Tip: This is usually because a character is not encoded. Like an ampersand.")
}
};
}
if (!elements.KnownXmlData.Any() &&
!elements.UnknownXmlData.Any())
{
return null;
}
// Finally, we convert each segment into a listing.
var successfullyParsedListings = new ConcurrentBag<ListingResult>();
var invalidData = new ConcurrentBag<ParsedError>();
Parallel.ForEach(elements.KnownXmlData, element =>
{
try
{
successfullyParsedListings.Add(new ListingResult
{
Listing = ConvertFromReaXml(element, DefaultCultureInfo, AddressDelimeter, isClearAllIsModified),
SourceData = element.ToString()
});
}
catch (Exception exception)
{
invalidData.Add(new ParsedError(exception.Message, element.ToString()));
}
});
return new ConvertToResult
{
Listings = successfullyParsedListings.Any()
? successfullyParsedListings.ToList()
: null,
UnhandledData = elements.UnknownXmlData != null &&
elements.UnknownXmlData.Any()
? elements.UnknownXmlData.Select(x => x.ToString()).ToList()
: null,
Errors = invalidData.Any()
? invalidData.ToList()
: null
};
}
示例12: GetDepStaffsCard
/// <summary>
/// Renvoi la list des departements avec leur employer
/// </summary>
/// <returns></returns>
public List<DepStaffCard> GetDepStaffsCard()
{
using (var db = new StationContext())
{
var depStaffCardList = new ConcurrentBag<DepStaffCard>();
var nd = new DepStaffCard("");
if (nd.StaffsList.Any()) { depStaffCardList.Add(nd); }
var deps = (db.Staffs.Where(s => !s.Person.IsDeleted).ToList()
.Where(s => string.IsNullOrEmpty(s.DepartementPrincipale) == false)
.Select(s => s.DepartementPrincipale)).Distinct().ToList();
Parallel.ForEach(deps, dep =>
{
depStaffCardList.Add(new DepStaffCard(dep));
});
return depStaffCardList.Any() ? depStaffCardList.OrderBy(d => d.DepartementName).ToList() : null;
}
}
示例13: GetMetrics
public async void GetMetrics()
{
try
{
Scope.Connect();
var datapoints = new ConcurrentBag<DataPoint>();
if (Counters == null) return; //no work to do.
Parallel.ForEach(Counters, counter =>
{
var datapoint = GetDataPoints(counter);
if (datapoint != null)
{
datapoint.ForEach(datapoints.Add);
}
});
if (datapoints.Any())
{
await _stackDriverPoster.SendBatchMetricsAsync(datapoints);
}
else
{
Log.Debug("No metrics were reported during this cycle.");
}
}
catch (Exception ex)
{
Log.Error("Exception in metric timer ", ex);
}
}
示例14: GenerateAssemblyReferenceGraph
public BidirectionalGraph<AssemblyVertex, EquatableEdge<AssemblyVertex>> GenerateAssemblyReferenceGraph(IEnumerable<Regex> exclusions, IEnumerable<Regex> ignoring, ConcurrentBag<string> files, bool verbose, bool checkAssemblyVersionMatch = true)
{
if (verbose) Console.WriteLine("Processing {0} files.", files.Count);
var edges = new ConcurrentBag<EquatableEdge<AssemblyVertex>>();
var vertices = new List<AssemblyVertex>();
var ignoreList = ignoring.ToList();
var excludeList = exclusions.ToList();
var current = 0;
var total = files.Count;
Parallel.ForEach(files, file =>
{
if (verbose) Console.Write("\rProcessing file: {0} of {1}", ++current, total);
AssemblyDefinition assembly;
try
{
assembly = AssemblyDefinition.ReadAssembly(new MemoryStream(_fileSystem.File.ReadAllBytes(file)));
}
catch (Exception)
{
if (verbose) Console.WriteLine("Skipping file as it does not appear to be a .Net assembly: {0}", file);
return;
}
//We need to load the assembly to ensure that the assembly name is the same as the file name (to be exact)
if (ignoreList.Any(i => i.IsMatch(assembly.Name.Name.ToLowerInvariant())))
{
if (verbose) Console.WriteLine("Ignoring file: {0}", file);
return;
}
//Check for 32bitness on our source assembly
var required32Bit = Required32BitSet(assembly);
var assemblyName = new AssemblyName(assembly.FullName);
//If we dont have references (I know, unlikely right?)
if (!assembly.MainModule.AssemblyReferences.Any())
{
vertices.Add(CreateAssemblyVertex(assemblyName.FullName, assemblyName.Name, true, Required32BitSet(assembly), excludeList));
return;
}
//Otherwise create edges for them...
foreach (var reference in assembly.MainModule.AssemblyReferences)
{
var foundFileMatch = files.Any(f => CheckDependentFileMatchesManifest(f, reference, checkAssemblyVersionMatch, required32Bit));
if (!foundFileMatch)
{
foundFileMatch = _gacResolver.AssemblyExists(reference.FullName);
}
if (!ignoreList.Any(i => i.IsMatch(reference.Name.ToLowerInvariant())))
edges.Add(CreateNewEdge(reference, foundFileMatch, required32Bit, assemblyName, excludeList));
else
if (verbose) Console.WriteLine("Ignoring: {0}",assemblyName.Name);
}
});
if (verbose) Console.WriteLine();
if (verbose) Console.WriteLine("Creating Graph...");
var graph = new BidirectionalGraph<AssemblyVertex, EquatableEdge<AssemblyVertex>>();
var allVertices = edges.Select(e => e.Source).Concat(edges.Select(e => e.Target)).Concat(vertices);
var distinctVertices = allVertices.Distinct();
graph.AddVertexRange(distinctVertices);
graph.AddEdgeRange(edges);
return graph;
}
示例15: DCAwareRoundRobinPolicyWithNodesChanging
public void DCAwareRoundRobinPolicyWithNodesChanging()
{
var hostList = new ConcurrentBag<Host>
{
TestHelper.CreateHost("0.0.0.1", "dc1"),
TestHelper.CreateHost("0.0.0.2", "dc2"),
TestHelper.CreateHost("0.0.0.3", "dc1"),
TestHelper.CreateHost("0.0.0.4", "dc2"),
TestHelper.CreateHost("0.0.0.5", "dc1"),
TestHelper.CreateHost("0.0.0.6", "dc2"),
TestHelper.CreateHost("0.0.0.7", "dc1"),
TestHelper.CreateHost("0.0.0.8", "dc2"),
TestHelper.CreateHost("0.0.0.9", "dc1"),
TestHelper.CreateHost("0.0.0.10", "dc2")
};
const string localDc = "dc1";
//to remove the host 3
var hostToRemove = hostList.First(h => TestHelper.GetLastAddressByte(h) == 3);
var clusterMock = new Mock<ICluster>();
clusterMock
.Setup(c => c.AllHosts())
.Returns(() =>
{
return hostList.ToList();
});
//Initialize the balancing policy
var policy = new DCAwareRoundRobinPolicy(localDc, 1);
policy.Initialize(clusterMock.Object);
var hostYielded = new ConcurrentBag<IEnumerable<Host>>();
Action action = () => hostYielded.Add(policy.NewQueryPlan(null, null).ToList());
//Invoke without nodes changing
TestHelper.ParallelInvoke(action, 100);
Assert.True(hostYielded.Any(hl => hl.Any(h => h == hostToRemove)));
var actionList = new List<Action>(Enumerable.Repeat<Action>(action, 1000));
actionList.Insert(200, () =>
{
var host = TestHelper.CreateHost("0.0.0.11", "dc1");
//raise event and then add
clusterMock.Raise(c => c.HostAdded += null, host);
hostList.Add(host);
});
actionList.Insert(400, () =>
{
var host = TestHelper.CreateHost("0.0.0.12", "dc1");
//first add and then raise event
hostList.Add(host);
clusterMock.Raise(c => c.HostAdded += null, host);
});
actionList.Insert(400, () =>
{
var host = hostToRemove;
hostList = new ConcurrentBag<Host>(hostList.Where(h => h != hostToRemove));
clusterMock.Raise(c => c.HostRemoved += null, host);
});
//Invoke it with nodes being modified
TestHelper.ParallelInvoke(actionList);
//Clear the host yielded so far
hostYielded = new ConcurrentBag<IEnumerable<Host>>();
//Invoke it a some of times more in parallel
TestHelper.ParallelInvoke(action, 100);
//The removed node should not be returned
Assert.False(hostList.Any(h => h == hostToRemove));
Assert.False(hostYielded.Any(hl => hl.Any(h => h == hostToRemove)));
}