Skip to content

Instantly share code, notes, and snippets.

@shadow-cs
Last active February 13, 2020 08:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shadow-cs/d6c64a187eda08f448abf144ee08c40b to your computer and use it in GitHub Desktop.
Save shadow-cs/d6c64a187eda08f448abf144ee08c40b to your computer and use it in GitHub Desktop.
NetMQ async exceptions
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.0</TargetFramework>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.2.0" />
<PackageReference Include="NetMQ" Version="4.0.0.272-pre" />
<PackageReference Include="xunit" Version="2.4.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.0" />
<PackageReference Include="coverlet.collector" Version="1.0.1" />
</ItemGroup>
</Project>
using System;
using System.Threading;
using Xunit;
using NetMQ;
using System.Threading.Tasks;
using NetMQ.Sockets;
namespace NetMQTest
{
public class UnitTest1
{
public async Task Method()
{
var cts = new CancellationTokenSource();
using var server = new ResponseSocket("inproc://1"); // bind
using var client = new RequestSocket("inproc://1"); // connect
client.SendFrame("Foo");
var s = server.ReceiveFrameString();
var task = client.ReceiveFrameStringAsync(cts.Token);
cts.Cancel();
await Task.Delay(100);
try
{
(s, _) = await task;
}
catch(TaskCanceledException e)
{
// Consume
}
server.SendFrame(s);
// This gets a little funky as the results are not deterministic (
// obviously ;-)), on my machine I get the following:
// With the Delay above and:
// await Task.Delay(10); - System.InvalidOperationException : An attempt was made to transition a task to a final state when it had already completed.
// await Task.Delay(1); - TaskSchedulerException: An exception was thrown by a TaskScheduler. ---> System.ObjectDisposedException: Cannot access a disposed object. (I was not able to verify this one on different computer - I got InvalidOperationException)
// await Task.Yield(); - No exception
// With the Delay above commented
// await Task.Delay(10); - System.InvalidOperationException : An attempt was made to transition a task to a final state when it had already completed.
// await Task.Delay(1); - System.InvalidOperationException : An attempt was made to transition a task to a final state when it had already completed. (but sometimes no exception is thrown)
// await Task.Yield(); - No exception
await Task.Delay(10);
}
[Fact]
public void Test1()
{
using var runtime = new NetMQRuntime();
var task = Method();
runtime.Run(task);
if (task.IsFaulted)
{
throw new Exception("Failed", task.Exception);
}
Assert.Equal(task.Status, TaskStatus.RanToCompletion);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment