That is method
public void SampleLimitCheck(float PhAverage, float AkmAverage, float CodAverage)
{
// Code...
}
I give float values to the function sometimes correct but some times appear as 0 in the function.
When i call Task.Run(() => _SampleCheck.SampleLimitCheck(_PhAvg, _AkmAvg, _CodAvg)); i see values are 0 in function. Not all the times. Sometimes 0 Sometimes i get the correct values.
But when i call _SampleCheck.SampleLimitCheck(_PhAvg, _AkmAvg, _CodAvg) i always catch the correct value.
What is wrong with Task.Run()?
CodePudding user response:
Not knowing how the code proceeds is a little difficult to know what it might be.
But since it's a Task, I can guess why you're reading the result before it's ready.
Task.Run(() => _SampleCheck.SampleLimitCheck(_PhAvg, _AkmAvg, _CodAvg)); Debug.WriteLine("-----");
In this example even before _SampleCheck.SampleLimitCheck finishes the Debug will be run.
If you need the result you must make sure the task is finished first.
CodePudding user response:
As it's currently written, it's hard to know exactly what you're question.
I guess
_PhAvgis member field.Run.Taskis executed before the correct value is obtained in the asynchronous thread, so_PhAvgis member default value.
Wrong code
Task.Run(() => _PhAvg = 10);
Task.Run(() => _SampleCheck.SampleLimitCheck(_PhAvg, _AkmAvg, _CodAvg));
Right code
await Task.Run(() => _PhAvg = 10);
await Task.Run(() => _SampleCheck.SampleLimitCheck(_PhAvg, _AkmAvg, _CodAvg));
The principle is to ensure that the _PhAvg assignment must precede the Task.Run.
