Skip to content

Commit

Permalink
add example for guard conditions
Browse files Browse the repository at this point in the history
  • Loading branch information
hoffmann-stefan committed May 19, 2023
1 parent 0307eba commit c12ec83
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
7 changes: 7 additions & 0 deletions rcldotnet_examples/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,16 @@ add_dotnet_executable(rcldotnet_example_client
${_assemblies_dep_dlls}
)

add_dotnet_executable(rcldotnet_guard_condition
RCLDotnetGuardCondition.cs
INCLUDE_DLLS
${_assemblies_dep_dlls}
)

install_dotnet(rcldotnet_talker DESTINATION lib/${PROJECT_NAME}/dotnet)
install_dotnet(rcldotnet_listener DESTINATION lib/${PROJECT_NAME}/dotnet)
install_dotnet(rcldotnet_example_service DESTINATION lib/${PROJECT_NAME}/dotnet)
install_dotnet(rcldotnet_example_client DESTINATION lib/${PROJECT_NAME}/dotnet)
install_dotnet(rcldotnet_guard_condition DESTINATION lib/${PROJECT_NAME}/dotnet)

ament_package()
50 changes: 50 additions & 0 deletions rcldotnet_examples/RCLDotnetGuardCondition.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
using System;
using System.Threading;
using System.Threading.Tasks;

using ROS2;

namespace ConsoleApplication
{
public static class RCLDotnetGuardCondition
{
static GuardCondition _guardCondition = null;

public static void Main(string[] args)
{
RCLdotnet.Init();

var node = RCLdotnet.CreateNode("guard_condition_example");

_guardCondition = node.CreateGuardCondition(GuardConditionTriggered);

Console.WriteLine($"RMWIdentifier: {RCLdotnet.GetRMWIdentifier()}");

_guardCondition.Trigger();
Console.WriteLine($"{DateTimeOffset.Now:O} ThreadId: {Environment.CurrentManagedThreadId} - Initial trigger of GuardCondition.");

RCLdotnet.Spin(node);
}

static void GuardConditionTriggered()
{
Console.WriteLine($"{DateTimeOffset.Now:O} ThreadId: {Environment.CurrentManagedThreadId} - GuardCondition was triggered.");
_ = TriggerAfterSomeTime();
}

static async Task TriggerAfterSomeTime()
{
// This is a multiple of the 500ms used in the loop in
// RCLdotnet.Spin(). So the guard condition will be triggered nearly
// at the same time as the wait times out. This is to test/reproduce
// if the combination of rcldotnet and the rmw implementation have
// an race-conditions in that case.
await Task.Delay(TimeSpan.FromSeconds(1));

// This will be called in an background worker thread as console
// applications don't have an SynchronizationContext by default.
_guardCondition.Trigger();
Console.WriteLine($"{DateTimeOffset.Now:O} ThreadId: {Environment.CurrentManagedThreadId} - Triggered GuardCondition.");
}
}
}

0 comments on commit c12ec83

Please sign in to comment.