It is a bit difficult for me to understand the following asynchronous usage. I have tested them locally and found that the actual result of both of them is the same, but I do not know in which scenarios the two should be used and whether there are potential problems?
The most basic requirement is that there is a property that does something. If true, it will start a thread (without interfering with the current thread) to perform a loop operation, and if false, it will close the loop operation.
public bool IsMaster
{
get { return _isMaster; }
set
{
_isMaster = value;
if (_isMaster)
{
if (_httpTask == null || _httpTask.IsCompleted || _httpTask.IsFaulted)
{
_httpTask = Task.Run(async () => await HandleHesApiRequest());
Logobject.LogDebug($"[HttpService]Master core,HTTP listenning started");
}
}
else
{
while (true)
{
//dispose resource
if (_httpTask == null || _httpTask.IsCompleted || _httpTask.IsFaulted)
{
Stop();
Logobject.LogDebug($"[HttpService]Worker core,HTTP listenning stopped");
break;
}
Thread.Sleep(2000);
}
}
}
}
The asynchronous method is like this
public async Task HandleHesApiRequest()
{
int relayCount = 2;
while (true)
{
if (!IsMaster)
{
Logobject.LogDebug($"[HttpService]Changed to worker core,HTTP listenning stopping...");
break;
}
else
{
//Do some job whether 'IsMaster==true'
}
await Task.Delay(xx)
}
Logobject.LogDebug($"[HttpService]Exit service...");
await Task.CompletedTask;
}
The question is I don't understand the difference between
_httpTask =Task.Run(()=>HandleHesApiRequest());
and
_httpTask = Task.Run(async () => await HandleHesApiRequest());
The Sdk is .Net Core 3.1