本文整理汇总了C#中BufferBlock.SendAsync方法的典型用法代码示例。如果您正苦于以下问题:C# BufferBlock.SendAsync方法的具体用法?C# BufferBlock.SendAsync怎么用?C# BufferBlock.SendAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类BufferBlock
的用法示例。
在下文中一共展示了BufferBlock.SendAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Process
public async Task Process(GamePointer gamePointer, List<PlayerState> players, BufferBlock<UpdatePacket> sendChannel)
{
if (_player.Dead)
{
return;
}
List<Square> changedSquares = gamePointer.Game.Update(_command, _player);
if (changedSquares.Count > 0)
{
var json = JSON.Serialize<Square[]>(changedSquares.ToArray());
var packet = new UpdatePacket()
{
Type = "square",
Data = json
};
await sendChannel.SendAsync(packet);
}
var player = JSON.Serialize<PlayerState>(_player);
var pp = new UpdatePacket()
{
Type = "player",
Data = player
};
await sendChannel.SendAsync(pp);
}
示例2: SendAsyncDeclinedTest
public void SendAsyncDeclinedTest ()
{
var target = new BufferBlock<int> ();
target.Complete ();
var task = target.SendAsync (1);
Assert.IsTrue (task.Wait (0));
Assert.IsFalse (task.Result);
}
示例3: SendAsyncAcceptedTest
public void SendAsyncAcceptedTest ()
{
var target = new BufferBlock<int> ();
var task = target.SendAsync (1);
Assert.IsTrue (task.Wait (0));
Assert.IsTrue (task.Result);
}
示例4: DecompressFastDataFlow
public static async Task DecompressFastDataFlow(Stream inputStream, Stream outputStream)
{
var buffer = new BufferBlock<DecompressionDetails>(new DataflowBlockOptions { BoundedCapacity = BoundedCapacity });
var compressorOptions = new ExecutionDataflowBlockOptions
{
MaxDegreeOfParallelism = MaxDegreeOfParallelism,
BoundedCapacity = BoundedCapacity
};
var writerOptions = new ExecutionDataflowBlockOptions
{
BoundedCapacity = BoundedCapacity,
SingleProducerConstrained = true
};
var compressor = new TransformBlock<DecompressionDetails, DecompressionDetails>(compressionDetails => Decompress(compressionDetails), compressorOptions);
var writer = new ActionBlock<DecompressionDetails>(compressionDetailsWithSize => Multiplex(buffer, outputStream, compressionDetailsWithSize), writerOptions);
buffer.LinkTo(compressor);
compressor.LinkTo(writer);
buffer.Completion.ContinueWith(task => compressor.Complete());
compressor.Completion.ContinueWith(task => writer.Complete());
byte[] size = new byte[sizeof(long)];
await inputStream.ReadAsync(size, 0, size.Length);
// convert the size to number
long sourceLength = BitConverter.ToInt64(size, 0);
int index = 0;
while (sourceLength > 0)
{
size = new byte[sizeof(long)];
await inputStream.ReadAsync(size, 0, size.Length);
// convert the size back to number
long chunkSize = BitConverter.ToInt64(size, 0);
if (chunkSize > sourceLength) throw new InvalidDataException("");
// read the compressed size
size = new byte[sizeof(int)];
await inputStream.ReadAsync(size, 0, size.Length);
// convert the size back to number
int storedSize = BitConverter.ToInt32(size, 0);
byte[] compressedData = new byte[storedSize];
int readCount = await inputStream.ReadAsync(compressedData, 0, compressedData.Length);
DecompressionDetails decompressionDetails = new DecompressionDetails
{
Bytes = compressedData,
ChunkSize = chunkSize,
Sequence = ++index
};
while (await buffer.SendAsync(decompressionDetails) != true) { }
sourceLength -= chunkSize;
if (sourceLength < chunkSize)
chunkSize = sourceLength;
if (sourceLength == 0)
buffer.Complete();
}
writer.Completion.Wait();
outputStream.Flush();
inputStream.Dispose();
outputStream.Dispose();
}
示例5: DoBulkParallel
Task DoBulkParallel()
{
BufferBlock<string> fileNameStore = new BufferBlock<string>();
int maxParallelism = ImageEngine.NumThreads == 1 ? 1 :
(ImageEngine.NumThreads == -1 ? Environment.ProcessorCount : ImageEngine.NumThreads);
// Define block to perform each conversion
var encoder = new TransformBlock<string, Tuple<byte[], string>>(file =>
{
byte[] data = null;
string filename = Path.GetFileNameWithoutExtension(file) + "." + ImageFormats.GetExtensionOfFormat(SaveFormat);
string path = Path.Combine(BulkUseSourceDestination ? Path.GetDirectoryName(file) : BulkSaveFolder, filename);
path = UsefulThings.General.FindValidNewFileName(path);
using (ImageEngineImage img = new ImageEngineImage(file))
{
try
{
data = img.Save(SaveFormat, SaveMipType, removeAlpha: GeneralRemovingAlpha, customMasks: customMasks);
}
catch (Exception e)
{
BulkConvertFailed.Add(path + " Reason: " + e.ToString());
}
}
BulkProgressValue++;
BulkStatus = $"Converting {BulkProgressValue}/{BulkProgressMax} images.";
return new Tuple<byte[], string>(data, path);
}, new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = maxParallelism, BoundedCapacity = maxParallelism });
// Define block to write converted data to disk
var diskWriter = new ActionBlock<Tuple<byte[], string>>(tuple =>
{
File.WriteAllBytes(tuple.Item2, tuple.Item1);
}, new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 2, BoundedCapacity = maxParallelism }); // Limit to 2 disk write operations at a time, but allow many to be stored in it's buffer.
// Link blocks together
fileNameStore.LinkTo(encoder, new DataflowLinkOptions { PropagateCompletion = true });
encoder.LinkTo(diskWriter, new DataflowLinkOptions { PropagateCompletion = true });
// Begin production
new Action(async () =>
{
foreach (var file in BulkConvertFiles)
await fileNameStore.SendAsync(file);
fileNameStore.Complete();
}).Invoke();
return diskWriter.Completion;
}
示例6: TestSendAsync_DelayedConsume
public async Task TestSendAsync_DelayedConsume()
{
var bb = new BufferBlock<int>(new DataflowBlockOptions { BoundedCapacity = 1 });
Task<bool> t = bb.SendAsync(1);
Assert.True(t.IsCompleted);
Assert.True(t.Result);
t = bb.SendAsync(2);
Assert.False(t.IsCompleted);
Assert.Equal(expected: 1, actual: await bb.ReceiveAsync());
Assert.True(await t);
t = bb.SendAsync(3);
bb.Complete();
Assert.Equal(expected: 2, actual: await bb.ReceiveAsync());
Assert.False(await t);
}
示例7: TestBoundedReceives
public async Task TestBoundedReceives()
{
for (int test = 0; test < 4; test++)
{
var bb = new BufferBlock<int>(new DataflowBlockOptions { BoundedCapacity = 1 });
Assert.True(bb.Post(0));
const int sends = 5;
for (int i = 1; i <= sends; i++)
{
Task<bool> send = bb.SendAsync(i);
Assert.True(await bb.OutputAvailableAsync()); // wait for previously posted/sent item
int item;
switch (test)
{
case 0:
IList<int> items;
Assert.True(bb.TryReceiveAll(out items));
Assert.Equal(expected: 1, actual: items.Count);
Assert.Equal(expected: i - 1, actual: items[0]);
break;
case 1:
Assert.True(bb.TryReceive(f => true, out item));
Assert.Equal(expected: i - 1, actual: item);
break;
case 2:
Assert.False(bb.TryReceive(f => f == i, out item));
Assert.True(bb.TryReceive(f => f == i - 1, out item));
Assert.Equal(expected: i - 1, actual: item);
break;
case 3:
Assert.Equal(expected: i - 1, actual: await bb.ReceiveAsync());
break;
}
}
// Receive remaining item
Assert.Equal(expected: sends, actual: await bb.ReceiveAsync());
bb.Complete();
await bb.Completion;
}
}
示例8: ProduceLogs
public void ProduceLogs(int count, int buffSize)
{
var bufferOptions = new DataflowBlockOptions() { BoundedCapacity = buffSize, MaxMessagesPerTask = 10 };
var writerOptions = new ExecutionDataflowBlockOptions() { BoundedCapacity = 10, MaxDegreeOfParallelism = 1, MaxMessagesPerTask = 10 };
var serializerOptions = new ExecutionDataflowBlockOptions() { BoundedCapacity = 80, MaxDegreeOfParallelism = 8, SingleProducerConstrained = true, MaxMessagesPerTask = 10 };
LogGenerator g = new LogGenerator();
var file = new StreamWriter("basic.async.srlz.buff.log", false);
BufferBlock<LogEntry> buffer = new BufferBlock<LogEntry>(bufferOptions);
TransformBlock<LogEntry, string> serializer = new TransformBlock<LogEntry, string>(
e => string.Format(e.format, e.parameters),
serializerOptions);
ActionBlock<string> writer = new ActionBlock<string>(s => file.WriteLine(s), writerOptions);
buffer.LinkTo(serializer, new DataflowLinkOptions() { PropagateCompletion = true });
serializer.LinkTo(writer, new DataflowLinkOptions() { PropagateCompletion = true });
for (int i = 0; i < count; i++)
{
g.Next();
var entry = new LogEntry() { format = g.FormatStr, parameters = new object[] { g.Param1, g.Param2, g.Param3, g.Param4, g.Param5, g.Param6 } };
buffer.SendAsync(entry).Wait();
}
buffer.Complete();
Completed = writer.Completion.ContinueWith(t => file.Close());
}
示例9: ProcessWebSocket
static async Task ProcessWebSocket(Websocket ws, ConnectionHub connectionHub, BufferBlock<GameTask> gameTasks)
{
var uc = new UserConnection(ws);
await connectionHub.Add(uc);
var hash = Guid.NewGuid().ToString();
var player = new PlayerState() { Name = "player", Color = "blue", Hash = hash };
var first = new PlayerInit() { Hash = hash, Height = 0, Width = 0 };
var json = JSON.Serialize(first);
var initPacket = new UpdatePacket() { Type = "init", Data = json };
var ip = JSON.Serialize(initPacket);
await uc.SendAsync(ip);
ReadWebsocket(ws, gameTasks, uc, player);
var initTask = new InitTask(uc, player);
await gameTasks.SendAsync(initTask);
await uc.Worker();
Console.WriteLine("disconnected");
//FIXME: this is never pushed to currently connected clients
player.Dead = true;
await connectionHub.Remove(uc);
}
示例10: ReadWebsocket
static async Task ReadWebsocket(Websocket ws, BufferBlock<GameTask> gameTasks, UserConnection uc, PlayerState player)
{
string next;
while ((next = await ws.ReadFrame()) != null)
{
var update = JSON.Deserialize<PlayerCommand>(next);
if (player.Dead)
{
//this is now checked in two places, but at least dead players won't send move commands to the main work channel
continue;
}
dynamic command = ParseCommand(update);
if (command == null)
{
continue;
}
var updatetask = new UpdateTask(command, player);
await gameTasks.SendAsync(updatetask);
}
uc.Closed = true;
await uc.SendAsync(null);
}
示例11: TestBufferBlockBounding
public void TestBufferBlockBounding()
{
const int WAIT_TIMEOUT = 4000; // wait at most 4 seconds for a particularly race-condition
// Test buffer doesn't exceed limit
{
bool localPassed = true;
for (int boundedCapacity = 1; boundedCapacity <= 3 && localPassed; boundedCapacity += 2)
{
var b = new BufferBlock<int>(new DataflowBlockOptions { BoundedCapacity = boundedCapacity });
for (int i = 0; i < boundedCapacity; i++)
{
var send = b.SendAsync(i);
Assert.True(send.Wait(0) && send.Result, "Send should succeed as capacity not yet reached");
}
for (int i = boundedCapacity; i < boundedCapacity + 2 && localPassed; i++)
{
Assert.True(b.Count == boundedCapacity, "Count should equal bounded capacity after all posts completed");
var t = b.SendAsync(i);
Assert.True(!t.IsCompleted, "Send should not have completed on a full buffer");
b.Receive();
Assert.True(t.Wait(WAIT_TIMEOUT), "The send should have completed before the timeout");
Assert.True(t.IsCompleted && t.Result, "The send should have completed successfully");
Assert.True(SpinWait.SpinUntil(() => b.Count == boundedCapacity, WAIT_TIMEOUT), "The count should be back at the bounded capacity after successful send");
}
int remainingCount = b.Count;
while (b.Count > 0)
{
remainingCount--;
int ignored;
Assert.True(b.TryReceive(out ignored), "Should have been able to successfully remove each item");
}
Assert.True(remainingCount == 0, "Should be no items left after removals");
}
Assert.True(localPassed, string.Format("{0}: Doesn't exceed limits", localPassed ? "Success" : "Failure"));
}
// Test correct ordering
{
bool localPassed = true;
for (int boundedCapacity = 1; boundedCapacity <= 3 && localPassed; boundedCapacity += 2)
{
int iters = boundedCapacity + 2;
var tasks = new Task<bool>[iters];
var b = new BufferBlock<int>(new DataflowBlockOptions { BoundedCapacity = boundedCapacity });
for (int i = 0; i < boundedCapacity; i++)
{
var t = b.SendAsync(i);
Assert.True(t.IsCompleted && t.Result, "Sends until capacity reached should complete immediately and successfully");
tasks[i] = t;
}
for (int i = boundedCapacity; i < iters; i++)
{
var t = b.SendAsync(i);
Assert.True(!t.IsCompleted, "Sends after capacity reached should not be completed");
tasks[i] = t;
}
for (int i = 0; i < iters && localPassed; i++)
{
if (i >= boundedCapacity & i < iters - boundedCapacity)
{
Assert.True(!tasks[i + boundedCapacity].IsCompleted, "Remaining sends should not yet be completed");
}
Assert.True(b.Receive() == i, "Received value should match sent value in correct order");
Assert.True(tasks[i].Wait(WAIT_TIMEOUT) && tasks[i].Result, "Next sender task should have completed");
}
}
Assert.True(localPassed, string.Format("{0}: Correct ordering", localPassed ? "Success" : "Failure"));
}
// Test declining
{
bool localPassed = true;
for (int boundedCapacity = 1; boundedCapacity <= 3 && localPassed; boundedCapacity += 2)
{
var b = new BufferBlock<string>(new DataflowBlockOptions { BoundedCapacity = boundedCapacity });
int total = boundedCapacity + 2;
var tasks = new Task<bool>[total];
for (int i = 0; i < total; i++)
{
tasks[i] = b.SendAsync(i.ToString());
}
for (int i = 0; i < total; i++)
{
Assert.True((i < boundedCapacity) == tasks[i].IsCompleted, "All sends below the capacity should have completed");
//.........这里部分代码省略.........
示例12: RunBufferBlockConformanceTests
public void RunBufferBlockConformanceTests()
{
bool localPassed;
// Do everything twice - once through OfferMessage and Once through Post
for (FeedMethod feedMethod = FeedMethod._First; feedMethod < FeedMethod._Count; feedMethod++)
{
Func<DataflowBlockOptions, TargetProperties<int>> bufferBlockFactory =
options =>
{
BufferBlock<int> bufferBlock = new BufferBlock<int>(options);
ActionBlock<int> actionBlock = new ActionBlock<int>(i => TrackCaptures(i), (ExecutionDataflowBlockOptions)options);
bufferBlock.LinkTo(actionBlock);
return new TargetProperties<int> { Target = bufferBlock, Capturer = actionBlock, ErrorVerifyable = false };
};
CancellationTokenSource cancellationSource = new CancellationTokenSource();
var defaultOptions = new ExecutionDataflowBlockOptions();
var dopOptions = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = Environment.ProcessorCount };
var mptOptions = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = Environment.ProcessorCount, MaxMessagesPerTask = 10 };
var cancellationOptions = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = Environment.ProcessorCount, MaxMessagesPerTask = 100, CancellationToken = cancellationSource.Token };
Assert.True(FeedTarget(bufferBlockFactory, defaultOptions, 1, Intervention.None, null, feedMethod, true));
Assert.True(FeedTarget(bufferBlockFactory, defaultOptions, 10, Intervention.None, null, feedMethod, true));
Assert.True(FeedTarget(bufferBlockFactory, dopOptions, 1000, Intervention.None, null, feedMethod, true));
Assert.True(FeedTarget(bufferBlockFactory, mptOptions, 10000, Intervention.None, null, feedMethod, true));
Assert.True(FeedTarget(bufferBlockFactory, mptOptions, 10000, Intervention.Complete, null, feedMethod, true));
Assert.True(FeedTarget(bufferBlockFactory, cancellationOptions, 10000, Intervention.Cancel, cancellationSource, feedMethod, true));
}
// Test chained Post/Receive
{
localPassed = true;
const int ITERS = 2;
var network = Chain<BufferBlock<int>, int>(4, () => new BufferBlock<int>());
for (int i = 0; i < ITERS; i++)
{
network.Post(i);
localPassed &= (((IReceivableSourceBlock<int>)network).Receive() == i);
}
Assert.True(localPassed, string.Format("{0}: Chained Post/Receive", localPassed ? "Success" : "Failure"));
}
// Test chained SendAsync/Receive
{
localPassed = true;
const int ITERS = 2;
var network = Chain<BufferBlock<int>, int>(4, () => new BufferBlock<int>());
for (int i = 0; i < ITERS; i++)
{
network.SendAsync(i);
localPassed &= (((IReceivableSourceBlock<int>)network).Receive() == i);
}
Assert.True(localPassed, string.Format("{0}: Chained SendAsync/Receive", localPassed ? "Success" : "Failure"));
}
// Test chained Post all then Receive
{
localPassed = true;
const int ITERS = 2;
var network = Chain<BufferBlock<int>, int>(4, () => new BufferBlock<int>());
for (int i = 0; i < ITERS; i++) localPassed &= network.Post(i) == true;
for (int i = 0; i < ITERS; i++) localPassed &= ((IReceivableSourceBlock<int>)network).Receive() == i;
Assert.True(localPassed, string.Format("{0}: Chained Post all then Receive", localPassed ? "Success" : "Failure"));
}
// Test chained SendAsync all then Receive
{
localPassed = true;
const int ITERS = 2;
var network = Chain<BufferBlock<int>, int>(4, () => new BufferBlock<int>());
var tasks = new Task[ITERS];
for (int i = 1; i <= ITERS; i++) tasks[i - 1] = network.SendAsync(i);
Task.WaitAll(tasks);
int total = 0;
for (int i = 1; i <= ITERS; i++) total += ((IReceivableSourceBlock<int>)network).Receive();
localPassed &= (total == ((ITERS * (ITERS + 1)) / 2));
Assert.True(localPassed, string.Format("{0}: Chained SendAsync all then Receive", localPassed ? "Success" : "Failure"));
}
// Test using a precanceled token
{
localPassed = true;
try
{
var cts = new CancellationTokenSource();
cts.Cancel();
var dbo = new DataflowBlockOptions { CancellationToken = cts.Token };
var bb = new BufferBlock<int>(dbo);
int ignoredValue;
IList<int> ignoredValues;
localPassed &= bb.LinkTo(new ActionBlock<int>(delegate { })) != null;
localPassed &= bb.SendAsync(42).Result == false;
localPassed &= bb.TryReceiveAll(out ignoredValues) == false;
localPassed &= bb.Post(42) == false;
localPassed &= bb.Count == 0;
localPassed &= bb.TryReceive(out ignoredValue) == false;
localPassed &= bb.Completion != null;
bb.Complete();
//.........这里部分代码省略.........
示例13: Execute
public Task Execute(CancellationToken token)
{
var options = new DataflowBlockOptions {CancellationToken = token};
_buffer = new BufferBlock<long>(options);
var hydrate = new TransformBlock<long, Summoner>(id =>
{
var summoner = _lookup.Hydrate(id);
return summoner;
}, new ExecutionDataflowBlockOptions { CancellationToken = token, MaxDegreeOfParallelism = 2 });
var store = new TransformBlock<Summoner, Summoner>(summoner =>
{
if (summoner != null)
_storage.Store(summoner);
return summoner;
}, new ExecutionDataflowBlockOptions {CancellationToken = token, MaxDegreeOfParallelism = 2});
var crawl = new TransformManyBlock<Summoner, FellowPlayerInfo>(async summoner =>
{
var summoners = new List<FellowPlayerInfo>();
var games = new List<PlayerGameStats>();
if (summoner != null)
{
await _crawler.Crawl(summoner, summoners.Add, games.Add);
}
return summoners;
}, new ExecutionDataflowBlockOptions {CancellationToken = token, MaxDegreeOfParallelism = 2});
var storeNextBatch = new ActionBlock<FellowPlayerInfo>(async info =>
{
if (info != null)
{
var data = await _lookup.Lookup(info.summonerId);
_storage.StoreWhenMissing(data);
}
}, new ExecutionDataflowBlockOptions {CancellationToken = token, MaxDegreeOfParallelism = 2});
_buffer.LinkTo(hydrate, new DataflowLinkOptions {PropagateCompletion = true});
hydrate.LinkTo(store, new DataflowLinkOptions {PropagateCompletion = true});
store.LinkTo(crawl, new DataflowLinkOptions {PropagateCompletion = true});
crawl.LinkTo(storeNextBatch, new DataflowLinkOptions {PropagateCompletion = true});
return Task.Run(async () =>
{
while (!token.IsCancellationRequested)
{
try
{
var batch = _producer.Produce((int) TimeSpan.FromDays(1).TotalMinutes, 30);
foreach (var id in batch)
await _buffer.SendAsync(id, token);
// Start the chain
_buffer.Complete();
// Wait until the chain is complete before iterating again
await storeNextBatch.Completion;
}
catch (Exception ex)
{
throw;
}
}
}, token);
}
示例14: SendAsyncPostponedAcceptedTest
public void SendAsyncPostponedAcceptedTest ()
{
var target =
new BufferBlock<int> (new DataflowBlockOptions { BoundedCapacity = 1 });
Assert.IsTrue (target.Post (1));
var task = target.SendAsync (1);
Assert.IsFalse (task.Wait (100));
Assert.AreEqual (1, target.Receive ());
Assert.IsTrue (task.Wait (1000));
Assert.IsTrue (task.Result);
}
示例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();
}));
}
}