本文整理汇总了C#中Task.Where方法的典型用法代码示例。如果您正苦于以下问题:C# Task.Where方法的具体用法?C# Task.Where怎么用?C# Task.Where使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Task
的用法示例。
在下文中一共展示了Task.Where方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: StartAsync
/// <inheritdocs />
public async Task StartAsync(CancellationToken cancellationToken)
{
if (this.started)
{
throw Error.InvalidOperation("The runner is already started.");
}
this.started = true;
var tasks = new Task[this.runners.Length];
Task task;
try
{
for (int i = 0; i < this.runners.Length; i++)
{
tasks[i] = this.runners[i].RunAsync(cancellationToken);
}
}
finally
{
task = Task.WhenAll(tasks.Where(t => t != null));
}
await task;
this.started = false;
}
示例2: WaitForAnyCompletion
/// <summary>
/// The server farms out work to Task values and this method needs to wait until at least one of them
/// has completed.
/// </summary>
private void WaitForAnyCompletion(IEnumerable<Task<ConnectionData>> e, Task[] other, CancellationToken cancellationToken)
{
var all = new List<Task>();
all.AddRange(e);
all.AddRange(other.Where(x => x != null));
try
{
Task.WaitAny(all.ToArray(), cancellationToken);
}
catch (OperationCanceledException)
{
// Thrown when the provided cancellationToken is cancelled. This is handled in the caller,
// here it just serves to break out of the WaitAny call.
}
}
示例3: Test_Partab_KV
private static void Test_Partab_KV()
{
//var cnn = ConnectionMultiplexer.Connect("172.17.1.70:10001,172.17.1.70:10002,172.17.1.70:10003,172.17.1.70:10004,172.17.1.70:10005,172.17.1.70:10006");
//var cnn = ConnectionMultiplexer.Connect("172.17.6.10:6379,172.17.6.11:6379,172.17.6.12:6379,172.17.6.13:6379,172.17.6.14:6379,172.17.6.15:6379");
var cnn = ConnectionMultiplexer.Connect("172.17.1.70:11111");
var db = cnn.GetDatabase();
long cid = 1200700000;
long gid = 146165;
var START = 0;
var COUNT = 1000;
var rnd = new Random();
var data = new Partab[COUNT];
for (int i = 0; i < data.Length; i++)
{
var d = new Partab
{
cid = rnd.Next(1000000, int.MaxValue),
gid = START + i,
FeedbackType = rnd.Next(1000000, int.MaxValue),
foldid = rnd.Next(1000000, int.MaxValue),
is_active_for_company = "y",
is_temporary = "y",
LabelType = i,
mdate = DateTime.Now,
pid = rnd.Next(1000000, int.MaxValue),
pnumber = "CC000043927J90250331000",
PostType = i,
public_label = i,
resume_source_id = i,
rid = rnd.Next(1000000, int.MaxValue),
rnumber = "JM346841194R90250000000",
rootid = 12007000 + i,
rversion = i,
uid = rnd.Next(1000000, int.MaxValue)
};
data[i] = d;
}
var tasks = new Task<bool>[COUNT];
var sw = Stopwatch.StartNew();
var expireSpan = new TimeSpan(90, 0, 0, 0);
for (int i = 0; i < data.Length; i++)
{
var item = data[i];
var json = JsonConvert.SerializeObject(item);
tasks[i] = db.StringSetAsync("gid_:" + item.gid.ToString(), json, expireSpan);
//db.StringSet("gid_:" + item.gid.ToString(), json, expireSpan);
}
try
{
Task.WaitAll(tasks);
sw.Stop();
cnn.Close();
}
catch (Exception ex)
{
var tt = tasks.Where(i => i.IsFaulted == true).ToList();
foreach (var item in ex.Data.Keys)
{
var o = ex.Data[item];
var test = o;
}
cnn.Close();
throw;
}
Console.WriteLine(sw.ElapsedMilliseconds);
}
示例4: SetASync
private static void SetASync()
{
var cnn = ConnectionMultiplexer.Connect("172.17.1.70:11111");
var db = cnn.GetDatabase();
var sw = Stopwatch.StartNew();
var count = 5;
var tasks = new Task<bool>[count];
Console.WriteLine("开始处理..." + count);
for (int i = 0; i < count; i++)
{
try
{
db.StringSet("name", "wgj");
//tasks[i] = db.StringSetAsync(i.ToString(), i);
//tasks[i].ContinueWith((t) =>
//{
// if (!t.Result)
// {
// Console.WriteLine(t.Result);
// }
//});
//System.Threading.Thread.Sleep(1000);
}
catch (Exception ex)
{
throw;
}
}
try
{
Task.WaitAll(tasks);
}
catch (Exception ex)
{
throw;
}
var failedTask = tasks.Where(i => i.Result == false);
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
Console.ReadLine();
}
示例5: DidAnyTaskStopp
/// <summary>
/// handle the situation when a thread dies and take appropriate steps
/// </summary>
/// <param name="tasks"></param>
/// <returns></returns>
private bool DidAnyTaskStopp( Task[] tasks)
{
if (Task.WhenAny (tasks).IsCompleted)
{
Log (string.Format ("UNEXPECTED ABORTION OF A THREAD! ABANDONING!"));
return true;
}
if (Task.WhenAny (tasks).IsFaulted)
{
Log (string.Format ("An expection has been detected! ABANDONING!"));
// get the exceptions available and log them
foreach (var task in tasks.Where (task => task.IsFaulted))
LogExceptions (task.Exception);
return true;
}
return false;
}
示例6: Chapter3Sample04_1
static void Chapter3Sample04_1()
{
var taskIndex = -1;
Task[] tasks = new Task[]
{
Task.Factory.StartNew(DoLeft),
Task.Factory.StartNew(DoRight),
Task.Factory.StartNew(DoCenter)
};
Task[] allTasks = tasks;
while (tasks.Length > 0)
{
taskIndex = Task.WaitAny(tasks);
Console.WriteLine("Finished task {0}.", taskIndex + 1);
tasks = tasks.Where((t) => t != tasks[taskIndex]).ToArray();
}
try
{
Task.WaitAll(allTasks);
}
catch (AggregateException ae)
{
ae.Handle(e =>
{
// Modify DoCenter to throw an InvalidOperationException to see this message.
if (e is InvalidOperationException)
{
Console.WriteLine("Saw expected exception.");
return true;
}
else
return false;
});
}
}
示例7: DisposeCompletedSubnodes
void DisposeCompletedSubnodes(Task<IQuadNode>[] finishedTasks)
{
foreach (var task in finishedTasks.Where(task => task.Status == TaskStatus.RanToCompletion))
{
((IDisposable)task.Result).Dispose();
}
}
示例8: Run
public override void Run()
{
GracefullyStopped = false;
//ThreadPool.SetMinThreads(3, 3);
Task[] tasks = new Task[]
{
Task.Factory.StartNew(() => {}),
Task.Factory.StartNew(() => {}),
Task.Factory.StartNew(() => {}),
//Task.Factory.StartNew(() => {}),
//Task.Factory.StartNew(() => {}),
//Task.Factory.StartNew(() => {}),
};
QueueSupport.ReportStatistics("Starting worker: " + CurrWorkerID, TimeSpan.FromDays(1));
while (!IsStopped)
{
try
{
Task.WaitAny(tasks);
if (IsStopped)
break;
int availableIx;
Task availableTask = WorkerSupport.GetFirstCompleted(tasks, out availableIx);
bool handledSubscriptionChain = PollAndHandleSubscriptionChain(tasks, availableIx, availableTask);
if (handledSubscriptionChain)
{
// TODO: Fix return value check
Thread.Sleep(1000);
continue;
}
bool handledMessage = PollAndHandleMessage(tasks, availableIx, availableTask);
if (handledMessage)
continue;
Thread.Sleep(1000);
}
catch (AggregateException ae)
{
foreach (var e in ae.Flatten().InnerExceptions)
{
ErrorSupport.ReportException(e);
}
Thread.Sleep(10000);
// or ...
// ae.Flatten().Handle((ex) => ex is MyCustomException);
}
/*
catch (MessagingException e)
{
if (!e.IsTransient)
{
Trace.WriteLine(e.Message);
throw;
}
Thread.Sleep(10000);
}*/
catch (OperationCanceledException e)
{
if (!IsStopped)
{
Trace.WriteLine(e.Message);
throw;
}
}
catch(Exception ex)
{
ErrorSupport.ReportException(ex);
throw;
}
}
Task.WaitAll(tasks);
foreach (var task in tasks.Where(task => task.Exception != null))
{
ErrorSupport.ReportException(task.Exception);
}
QueueSupport.ReportStatistics("Stopped: " + CurrWorkerID, TimeSpan.FromDays(1));
GracefullyStopped = true;
}
示例9: concurrent_access_are_detected
public void concurrent_access_are_detected()
{
IActivityMonitor monitor = new ActivityMonitor();
if( TestHelper.LogsToConsole ) monitor.Output.RegisterClient( new ActivityMonitorConsoleClient() );
// Artficially slows down logging to ensure that concurrent access occurs.
monitor.Output.RegisterClient( new ActionActivityMonitorClient( () => Thread.Sleep( 50 )) );
object lockTasks = new object();
object lockRunner = new object();
int enteredThread = 0;
Action getLock = () =>
{
lock( lockTasks )
{
Interlocked.Increment( ref enteredThread );
lock( lockRunner )
Monitor.Pulse( lockRunner );
Monitor.Wait( lockTasks );
}
};
Task[] tasks = new Task[]
{
new Task( () => { getLock(); monitor.Info().Send( "Test T1" ); } ),
new Task( () => { getLock(); monitor.Info().Send( new Exception(), "Test T2" ); } ),
new Task( () => { getLock(); monitor.Info().Send( "Test T3" ); } )
};
Parallel.ForEach( tasks, t => t.Start() );
lock( lockRunner )
while( enteredThread < tasks.Length )
Monitor.Wait( lockRunner );
lock( lockTasks )
Monitor.PulseAll( lockTasks );
Assert.Throws<AggregateException>( () => Task.WaitAll( tasks ) );
CollectionAssert.AllItemsAreInstancesOfType( tasks.Where( x => x.IsFaulted ).
SelectMany( x => x.Exception.Flatten().InnerExceptions ),
typeof( InvalidOperationException ) );
Assert.DoesNotThrow( () => monitor.Info().Send( "Test" ) );
}
示例10: consumerProducerWithBlockingCollection
//Consumer/Producer w/ blockingCollection
public static void consumerProducerWithBlockingCollection()
{
int numCores = System.Environment.ProcessorCount;
int max = 10000;
string[] records = new string[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
var sw = System.Diagnostics.Stopwatch.StartNew();
sw.Restart();
//shared thred-safe collection
BlockingCollection<string> work = new BlockingCollection<string>(max);
var tf = new TaskFactory(TaskCreationOptions.LongRunning, TaskContinuationOptions.None);
Task producer = tf.StartNew(() =>
{
//read file each line and add to the collection
for (int i = 0; i < 10; i++)
work.Add(records[i]);
//producer signals its done
work.CompleteAdding();
});
Dictionary<int, int> RESULTLIST = new Dictionary<int, int>();
Task<Dictionary<int, int>>[] consumers = new Task<Dictionary<int, int>>[numCores];
for (int i = 0; i < numCores; i++)
{
consumers[i] = tf.StartNew<Dictionary<int, int>>(() =>
{
Dictionary<int, int> localD = new Dictionary<int, int>();
while (!work.IsCompleted)
{
try
{
string line = work.Take();
//do operation ...
//update local Dictionary
localD.Add(1, 1);
}
catch (ObjectDisposedException) {/*ignore*/}
catch (InvalidOperationException) {/*ignore*/}
}
return localD;
});
}
//main Thread to harvest Results
int completed = 0;
while (completed < numCores)
{
//WaitAllOneByOne Pattern
int taskIndex = Task.WaitAny(consumers);
Dictionary<int, int> localD = consumers[taskIndex].Result;
//Process the local Dictionary into RESULTLIST
completed++;
consumers = consumers.Where(t => t != consumers[taskIndex]).ToArray();
}
var sort = RESULTLIST
.OrderByDescending(r => r.Value)
.OrderBy(r => r.Key).ToList();
//Print results
long timems = sw.ElapsedMilliseconds;
//check for Aggregated Exceptions
try
{
producer.Wait();
}
catch (AggregateException ae)
{
ae = ae.Flatten();
foreach (var e in ae.InnerExceptions) { }
}
catch (Exception) { }
}
示例11: ConcurrentTasksCompleted
static void ConcurrentTasksCompleted(Task<byte[]>[] tasks)
{
int failures = tasks.Where(t => t.Exception != null).Count();
Console.WriteLine("Concurrent result: {0} successes and {1} failures", tasks.Length - failures, failures);
}
示例12: send2All
/// <summary>
/// Sends a message to all matching listeners. This method is thread-safe!
/// </summary>
/// <param name="message">The message with the channel and command.</param>
/// <param name="kind">The matching kind of listeners. Thus, you can send a message only to Ocean servers, component servers or to both.</param>
/// <returns>All received answers.</returns>
public IEnumerable<IICCCMessage> send2All(IICCCMessage message, byte kind)
{
// No message? No answer!
if(message == null)
{
return new IICCCMessage[0];
}
// We read the cache, thus, ensure the read access:
this.cacheLock.EnterReadLock();
try
{
// Convert the message to data:
var data = ICCCProcessor.INSTANCE.convertMessage2Data(message);
// No valid message?
if(data == null || data.Count < 2) // channel + command = 2
{
return new IICCCMessage[0];
}
// Get all matching listeners:
var matchingListeners = this.icccListenerCache.Where(n => n.IsActive && (kind == ICCCKind.KindALL || n.Kind == kind)).Where(n => n.Channel == message.getChannel() && n.Command == message.getCommand()).ToArray();
// No matching listener?
if(matchingListeners.Length == 0)
{
return new IICCCMessage[0];
}
// Space for all threads and results:
var tasks = new Task<IICCCMessage>[matchingListeners.Length];
// Loop over all matching listeners:
for(var n = 0; n < matchingListeners.Length; n++)
{
// Get an listener:
var listener = matchingListeners[n];
// Start a new thread:
tasks[n] = Task.Run<IICCCMessage>(() =>
{
// Send the message and read the answer:
var answerData = this.sendMessage(data, listener);
// Create another empty instance for the answer:
var type = message.getAnswerObject().GetType();
var answerObj = type.GetConstructors().First(info => !info.GetParameters().Any()).Invoke(null) as IICCCMessage;
// Create the answer's message and return it:
return ICCCProcessor.INSTANCE.convertData2Message(answerData, answerObj);
});
}
// Wait for all answers:
Task.WaitAll(tasks);
return tasks.Where(n => n.Result != null).Select(t => t.Result).ToArray();
}
catch
{
return new IICCCMessage[0];
}
finally
{
this.cacheLock.ExitReadLock();
}
}
示例13: WaitFirstTask
/// <summary>
/// 逐个输出任务完成的通知
/// </summary>
static void WaitFirstTask()
{
var taskIndex = -1;
Task[] tasks = new Task[]{
Task.Factory.StartNew(DoSomething1),
Task.Factory.StartNew(DoSomething2),
Task.Factory.StartNew(DoSomething3)
};
Task[] allTasks = tasks;
// 逐个输出任务完成的通知
while (tasks.Length > 0)
{
taskIndex = Task.WaitAny(tasks);
Console.WriteLine("Finished task {0}.", taskIndex + 1);
tasks = tasks.Where((t) => t != tasks[taskIndex]).ToArray();
}
try
{
Task.WaitAll(allTasks);
}
catch (AggregateException ae)
{
}
}
示例14: CleanupFailedOpenAsync
async Task CleanupFailedOpenAsync(Task<IMediaReader>[] readerTasks)
{
Debug.WriteLine("SmMediaManager.CleanupFailedOpenAsync() state " + State);
_playbackCancellationTokenSource.Cancel();
if (null == _readers && null != readerTasks)
{
// Clean up any stragglers.
_readers = readerTasks.Where(
r =>
{
if (null == r)
return false;
var readerException = r.Exception;
if (null != readerException)
{
Debug.WriteLine("SmMediaManager.CleanupFailedOpenAsync(): reader create failed: " + readerException.Message);
return false;
}
return r.IsCompleted;
})
.Select(r => r.Result)
.ToArray();
await CloseReadersAsync().ConfigureAwait(false);
DisposeReaders();
}
if (null != _readerManager)
{
_readerManager.DisposeSafe();
_readerManager = null;
}
}