I am trying to build a ASP.NET Core application that should receive information in unmanaged code and present this information to the web users. When the ASP.NET Core application starts it will start up a background service that will register a callback in the unmanaged code.
In the Main function I have registered the background service to start:
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
}).ConfigureServices(services =>
{
services.AddHostedService<ReadService>();
})
;
}
Then in my background service I register the callback in the unmanaged code:
public class ReadService: BackgroundService
{
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void CSCALLBACK([In, MarshalAs(UnmanagedType.LPStr)] string a);
[DllImport("managed_service_wrapper", CallingConvention = CallingConvention.Cdecl)]
public static extern int SetCallback(CSCALLBACK callback);
public ReadService()
{
CSCALLBACK cb = OnNewUpdates;
var a = SetCallback(cb);
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
//something
}
}
static void OnNewUpdates(string a)
{
//something
}
}
When calling the SetCallback function the unmanaged code will start listen for updates but will return when the start listening is started.
Will this even work? When the callback is triggered will it block the rest of the code? What should I use in OnNewUpdates to signal to ExecuteAsync that there is a new update?
Update 2020-11-02 Maybe my question wasn't so clear so to make it more clear:
- What should I put in the ExecuteAsync function? Nothing?
- Is it wrong to implement my service as a BackgroundService?