Home > Software engineering >  C# function float argument takes 0 value inside the function when i call func Task.Run
C# function float argument takes 0 value inside the function when i call func Task.Run

Time:01-02

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

  • _PhAvg is member field.
  • Run.Task is executed before the correct value is obtained in the asynchronous thread, so _PhAvg is 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.

  • Related