Home > other >  Function float argument takes 0 value inside the function when I call func Task.Run
Function float argument takes 0 value inside the function when I call func Task.Run

Time:01-02

private float _PhAvg;

_pHAVg assign

_PhAvg = DatabaseReader._Parameters
    .SingleOrDefault(x => x.SpecificReg == RegCodes.phScode)
    ?.CurrentValue?.Average() ?? -9999; 

check _pHAvg

Console.WriteLine("pH :" _pHAVg); Output pH:6,77

Call method

Task.Run(() => _SampleCheck.SampleLimitCheck(_PhAvg, _AkmAvg, _CodAvg));

And that is SampleLimitCheck method

public void SampleLimitCheck(float PhAverage, float AkmAverage, float CodAverage)
{
    Console.WriteLine("pH :"   PhAverage);
}

Check PhAverage

Console.WriteLine("pH :" PhAverage); Output pH:0

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