本文整理汇总了C#中BufferBlock.ReceiveAsync方法的典型用法代码示例。如果您正苦于以下问题:C# BufferBlock.ReceiveAsync方法的具体用法?C# BufferBlock.ReceiveAsync怎么用?C# BufferBlock.ReceiveAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类BufferBlock
的用法示例。
在下文中一共展示了BufferBlock.ReceiveAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: script
protected override async Task script(Player p, BufferBlock<string> input)
{
// todo: what happens if the player quits during chargen? do we get an exception?
// todo: ignore input when not expecting it
p.Tell(@"Welcome to Chargen.
Your GUID is {0}.", p.Guid);
var name = "";
while (name == "")
{
p.Tell("\nWhat is your name? >");
string s = (await input.ReceiveAsync()).Trim();
Action<string> e = (m => p.Tell(m, "'" + s + "'"));
// TODO: check if name is already in use and the user would like to disambiguate?
// One-character names are allowed if they're not some English alphabet character, basically.
// Otherwise, names must be at least two characters after trimming.
// The name must also contain at least one unicode 'letter'.
if (s.Length < 1)
e("{0} is too short. Please choose a name at least two characters in length.");
else if (((s[0] >= 'a' && s[0] <= 'z') || (s[0] >= 'A' && s[0] <= 'Z')) && s.Length == 1)
e("{0} is too short. Please choose a name at least two characters in length.");
else if (s.Length > 16)
e("That name's pretty long! Could you squeeze it down to no more than 16 characters?!");
else if (s.All(c => !Char.IsLetter(c)))
e("{0} doesn't contain any letters. Chuck one in for us, would you?");
else if (s.Contains("'") || s.Contains('"') || s.EndsWith(".") || s.EndsWith(",") || s.EndsWith(";") || s.EndsWith(">"))
e("{0} contains a ' or a \" or ends with a '.', ',', '>', or ';'. You can't do this - sorry. It'd make the game look odd.");
else if ((s.Count(c => c == '(') != s.Count(c => c == ')')) || (s.Count(c => c == '[') != s.Count(c => c == ']'))
|| (s.Count(c => c == '{') != s.Count(c => c == '}')) || (s.Count(c => c == '<') != s.Count(c => c == '>')))
e("{0} contains mismatched brackets, a real pet hate of mine. Please make sure there's the same number of open as close brackets for each bracket type.");
else
{
p.Tell("You entered your name as '{0}'. Is this the handle you wish to use? y/n >", s);
string yn = (await input.ReceiveAsync()).Trim().ToLower();
if (yn.StartsWith("y") || new List<string> { "yes", "y", "yep", "you bet", "of course", "absolutely",
"very yes", "very much so", "indubitably", "hell yes", "hell yeah", "yea", "ye" }.Contains(yn))
name = s;
else
p.Tell("Okay. Let's have another go.");
}
}
p.Tell("That's all I needed to know. Let's begin!");
// actually set the properties
p.Name = name;
}
示例2: PushUpdates
static async Task PushUpdates(BufferBlock<UpdatePacket> sendQueue, ConnectionHub connectionHub)
{
while (true)
{
var next = await sendQueue.ReceiveAsync();
var json = JSON.Serialize<UpdatePacket>(next);
await connectionHub.Broadcast(json);
}
}
示例3: FsharpWorker
static FsharpWorker()
{
requestQueue = new BufferBlock<FsharpRequest>();
worker = Task.Run(async ()=>{
while(true){
var request = await requestQueue.ReceiveAsync();
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "fsharpi";
startInfo.Arguments = "--nologo";
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
startInfo.UseShellExecute = false;
var process = Process.Start(startInfo);
var reader = process.StandardOutput;
var writer = process.StandardInput;
using(var sr = new StringReader(request.Body)){
string line;
while((line=await sr.ReadLineAsync())!=null){
writer.WriteLine(line);
}
}
writer.WriteLine(";;");
writer.WriteLine("#quit;;");
string output;
string response="";
while((output = await reader.ReadLineAsync())!=null){
response+=output;
response+="\r\n";
}
if (!process.WaitForExit(200)){
Console.WriteLine("fsharpi process failed to quit in time");
}
request.SetResult(response);
}
});
}
示例4: RunGame
static async Task RunGame()
{
var connectionHub = new ConnectionHub();
var gameTasks = new BufferBlock<GameTask>();
var sendChannel = new BufferBlock<UpdatePacket>();
var players = new List<PlayerState>();
var gp = new GamePointer();
gp.Game = new Sweeper();
Task listen = Listen(connectionHub, gameTasks);
Task hubworker = connectionHub.StartWorker();
Task pushupdates = PushUpdates(sendChannel, connectionHub);
while (true)
{
var task = await gameTasks.ReceiveAsync();
await task.Process(gp, players, sendChannel);
}
}
示例5: HandleOutgoingData
private async Task HandleOutgoingData(StreamWriter writer,
CancellationToken cancellationToken)
{
var dataToSend = new BufferBlock<string>();
var statusUpdater = new Action<string>(state => dataToSend.Post(state));
try
{
StateUpdated += statusUpdater;
while (!cancellationToken.IsCancellationRequested)
{
var data = await dataToSend.ReceiveAsync(cancellationToken);
await writer.WriteLineAsync(data, cancellationToken);
}
}
finally
{
StateUpdated -= statusUpdater;
}
}
示例6: RunBufferBlockAsync
public static async Task RunBufferBlockAsync(int count)
{
var cancellationToken = CancellationToken.None;
var target = new BufferBlock<string>();
var PostTasks = new Task[count];
var dequeueTasks = new Task<string>[count];
var PostSetupTask = Task.Run(() =>
{
for (int i = 0; i < count; i++)
{
var item = "HVQFSW613ACT65DOS2ILBA4G4QB3UP3K4PPZPB7UZ771SX9TX7DVNZR82W1TSHWDBZHIE8V6CGILADRFQ3QA76BOYA4T3XS7A8OQ3I2FCT8X04L2GXR3RY23WB2A0ZLNT58WCMZTY54PRPOVVENCMOJMCZC6D85H9HPGJ58BBOHN7PJ0G3QTDSB8K4ACT26QXG5D30WI";
PostTasks[i] = Task.Run(() => target.Post(item));
}
});
var dequeueSetupTask = Task.Run(() =>
{
for (int i = 0; i < count; i++)
{
dequeueTasks[i] = target.ReceiveAsync(cancellationToken);
}
});
await Task.WhenAll(PostSetupTask, dequeueSetupTask);
await Task.WhenAll(dequeueTasks);
await Task.WhenAll(PostTasks);
if (target.Count != 0)
{
System.Console.WriteLine("BufferBlock - Not empty");
}
}
示例7: TestAsObservableAndAsObserver_DataPropagation
public async Task TestAsObservableAndAsObserver_DataPropagation()
{
// Test that preset data flows correctly
{
var bb = new BufferBlock<int>();
bb.PostRange(0, 2);
bb.Complete();
int nextValueExpected = 0;
var ab = new ActionBlock<int>(i => {
Assert.True(i == nextValueExpected, string.Format("Expected next value to be {0} but got {1}", nextValueExpected, i));
nextValueExpected++;
});
bb.AsObservable().Subscribe(ab.AsObserver());
await ab.Completion;
}
// Test that new data flows correctly
{
int nextValueExpected = -2;
var ab = new ActionBlock<int>(i => {
Assert.True(i == nextValueExpected, string.Format("Expected next value to be {0} but got {1}", nextValueExpected, i));
nextValueExpected++;
});
var bb = new BufferBlock<int>();
bb.AsObservable().Subscribe(ab.AsObserver());
bb.PostRange(-2, 0);
bb.Complete();
await ab.Completion;
}
// Test that unsubscribing stops flow of data and stops completion
{
var target = new BufferBlock<int>();
var source = new BufferBlock<int>();
using (source.AsObservable().Subscribe(target.AsObserver()))
{
source.PostItems(1, 2);
Assert.Equal(expected: 1, actual: await target.ReceiveAsync());
Assert.Equal(expected: 2, actual: await target.ReceiveAsync());
}
source.Post(3);
var wb = new WriteOnceBlock<int>(i => i);
source.LinkTo(wb);
await wb.Completion;
source.Complete();
await source.Completion;
Assert.False(target.Completion.IsCompleted);
}
}
示例8: TestReceiveAsync_LongChain
public async Task TestReceiveAsync_LongChain()
{
const int Length = 10000;
var bb = new BufferBlock<int>();
Task t = bb.ReceiveAsync();
for (int i = 1; i < Length; i++)
{
t = t.ContinueWith(_ => bb.ReceiveAsync(),
CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default).Unwrap();
}
bb.PostRange(0, Length);
await t;
}
示例9: TestReceiveAsync_ManyInOrder
public async Task TestReceiveAsync_ManyInOrder()
{
var bb = new BufferBlock<int>();
Task<int>[] tasks = Enumerable.Range(0, 100).Select(_ => bb.ReceiveAsync()).ToArray();
Assert.All(tasks, t => Assert.False(t.IsCompleted));
bb.PostRange(0, tasks.Length);
for (int i = 0; i < tasks.Length; i++)
{
Assert.Equal(expected: i, actual: await tasks[i]);
}
}
示例10: TestReceive_CanceledSource
public async Task TestReceive_CanceledSource()
{
foreach (bool beforeReceive in DataflowTestHelpers.BooleanValues)
{
var cts = new CancellationTokenSource();
var bb = new BufferBlock<int>(new DataflowBlockOptions { CancellationToken = cts.Token });
if (beforeReceive)
{
cts.Cancel();
}
else
{
var ignored = Task.Run(() => cts.Cancel()); // as elsewhere, this test should always succeed, but is racy as to what's being tested
}
Assert.Throws<InvalidOperationException>(() => bb.Receive());
}
foreach (bool beforeReceive in DataflowTestHelpers.BooleanValues)
{
var cts = new CancellationTokenSource();
var bb = new BufferBlock<int>(new DataflowBlockOptions { CancellationToken = cts.Token });
if (beforeReceive)
{
cts.Cancel();
}
var t = bb.ReceiveAsync();
if (!beforeReceive)
{
cts.Cancel();
}
await Assert.ThrowsAsync<InvalidOperationException>(() => t);
}
}
示例11: TestReceive_Cancellation
public async Task TestReceive_Cancellation()
{
var bb = new BufferBlock<int>();
// Cancel before Receive/ReceiveAsync
Assert.ThrowsAny<OperationCanceledException>(() => bb.Receive(new CancellationToken(canceled: true)));
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => bb.ReceiveAsync(new CancellationToken(canceled: true)));
// Cancel after Receive/ReceiveAsync but before data
{
var cts = new CancellationTokenSource();
var ignored = Task.Run(() => cts.Cancel()); // as elsewhere, this test should always succeed, but is racy as to what's being tested
Assert.ThrowsAny<OperationCanceledException>(() => bb.Receive(cts.Token));
}
{
var cts = new CancellationTokenSource();
var t = bb.ReceiveAsync(cts.Token);
cts.Cancel();
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => bb.ReceiveAsync(cts.Token));
}
// Cancel after data received
{
var cts = new CancellationTokenSource();
var ignored = Task.Run(() => bb.Post(1)); // as elsewhere, this test should always succeed, but is racy as to what's being tested
Assert.Equal(expected: 1, actual: bb.Receive(cts.Token));
cts.Cancel(); // just checking to make sure there's no exception
}
{
var cts = new CancellationTokenSource();
var t = bb.ReceiveAsync(cts.Token);
bb.Post(2);
Assert.Equal(expected: 2, actual: await t);
cts.Cancel(); // just checking to make sure there's no exception }
}
}
示例12: TestSendAsync_Canceled
public async Task TestSendAsync_Canceled()
{
CancellationTokenSource cts;
var bb = new BufferBlock<int>(new DataflowBlockOptions { BoundedCapacity = 1 });
Task<bool> t = bb.SendAsync(1, new CancellationToken(canceled: true));
Assert.True(t.IsCanceled);
t = bb.SendAsync(2, new CancellationToken(canceled: false));
Assert.True(t.IsCompleted);
Assert.True(t.Result);
cts = new CancellationTokenSource();
t = bb.SendAsync(3, cts.Token);
Assert.False(t.IsCompleted);
cts.Cancel();
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => t);
Assert.Equal(expected: 2, actual: await bb.ReceiveAsync());
bb.Complete();
await bb.Completion;
foreach (bool withCancellation in DataflowTestHelpers.BooleanValues)
{
var target = new DelegatePropagator<int, int>();
target.OfferMessageDelegate = (messageHeader, messageValue, source, consumeToAccept) => {
if (source == null)
return DataflowMessageStatus.Declined;
Assert.Equal(expected: withCancellation, actual: consumeToAccept);
if (consumeToAccept)
{
Assert.NotNull(source);
bool consumed;
source.ConsumeMessage(messageHeader, target, out consumed);
Assert.True(consumed);
}
return DataflowMessageStatus.Accepted;
};
t = withCancellation ?
target.SendAsync(1, new CancellationTokenSource().Token) :
target.SendAsync(2);
Assert.True(await t);
}
}
示例13: TestMultiplePostponesFromSameSource
public async Task TestMultiplePostponesFromSameSource()
{
var source = new BufferBlock<int>();
// Fill a target
var target1 = new BufferBlock<int>(new DataflowBlockOptions { BoundedCapacity = 1 });
target1.Post(1);
// Link to the target from a source; the message should get postponed
source.Post(2);
IDisposable unlink = source.LinkTo(target1);
Assert.Equal(expected: 1, actual: source.Count);
// Unlink, then relink; message should be offered again
unlink.Dispose();
source.LinkTo(target1);
Assert.Equal(expected: 1, actual: source.Count);
// Now receive to empty target1; it should then take the message from the source
Assert.Equal(expected: 1, actual: await target1.ReceiveAsync());
Assert.Equal(expected: 2, actual: await target1.ReceiveAsync());
}
示例14: TestFaultingAndCancellation
public async Task TestFaultingAndCancellation()
{
foreach (int boundedCapacity in new[] { DataflowBlockOptions.Unbounded, 1 })
foreach (bool fault in DataflowTestHelpers.BooleanValues)
{
var cts = new CancellationTokenSource();
var bb = new BufferBlock<int>(new DataflowBlockOptions { CancellationToken = cts.Token, BoundedCapacity = boundedCapacity });
Task<bool>[] sends = Enumerable.Range(0, 4).Select(i => bb.SendAsync(i)).ToArray();
Assert.Equal(expected: 0, actual: await bb.ReceiveAsync());
Assert.Equal(expected: 1, actual: await bb.ReceiveAsync());
if (fault)
{
Assert.Throws<ArgumentNullException>(() => ((IDataflowBlock)bb).Fault(null));
((IDataflowBlock)bb).Fault(new InvalidCastException());
await Assert.ThrowsAsync<InvalidCastException>(() => bb.Completion);
}
else
{
cts.Cancel();
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => bb.Completion);
}
await Task.WhenAll(sends);
Assert.Equal(expected: 0, actual: bb.Count);
}
}
示例15: TestProducerConsumer
public async Task TestProducerConsumer()
{
foreach (TaskScheduler scheduler in new[] { TaskScheduler.Default, new ConcurrentExclusiveSchedulerPair().ExclusiveScheduler })
foreach (int maxMessagesPerTask in new[] { DataflowBlockOptions.Unbounded, 1, 2 })
foreach (int boundedCapacity in new[] { DataflowBlockOptions.Unbounded, 1, 2 })
{
const int Messages = 100;
var bb = new BufferBlock<int>(new DataflowBlockOptions
{
BoundedCapacity = boundedCapacity,
MaxMessagesPerTask = maxMessagesPerTask,
TaskScheduler = scheduler
});
await Task.WhenAll(
Task.Run(async delegate { // consumer
int i = 0;
while (await bb.OutputAvailableAsync())
{
Assert.Equal(expected: i, actual: await bb.ReceiveAsync());
i++;
}
}),
Task.Run(async delegate { // producer
for (int i = 0; i < Messages; i++)
{
await bb.SendAsync(i);
}
bb.Complete();
}));
}
}