Scenario: I want to call an async task from a sync method but it's an independent task from which I don't need any return and I plan control all exceptions in the task, so no exception will be launched.
What's the best solution to call it without deadlocking and trying to spend less resources?
Example:
//Sync Method
public MySyncMethod()
{
//Maybe this?
Task.Run(() => KeepAlive(keepAliveSec));
//or this?
KeepAlive(keepAliveSec).GetAwaiter();
//Any other better option?
}
/// <summary>
/// Starts Heartbeat, Async Task
/// </summary>
/// <param name="sec"></param>
/// <returns></returns>
public async Task KeepAlive(int sec)
{
try
{
while (!CancelationToken.IsCancellationRequested)
{
if ((DateTime.Now - LastMessageDate).Seconds<sec)
{
SendMessage(new MessageV4() { MsgType = MsgTypeEnum.HeartBeat });
}
await Task.Delay(60000);
}
}
catch (Exception ex)
{
//Just do what you want to control any Exception
Log.Debug(ex);
}
}
PS -I've searched here before, but still I've not found a clear answer