await Task.Run(() =>
{
if (tempFormulaFibonacci.Contains($"+ ({multiplicatorsSlider.Value}*numberPosition)"))
{
finalFormula = tempFormulaFibonacci.Replace($"+ ({multiplicatorsSlider.Value}*numberPosition)", $"+ {multiplicatorsSlider.Value}*" + Convert.ToString(++temp));
tempFormulaFibonacci = Convert.ToString(finalFormula);
}
if (tempFormulaFibonacci.Contains("numberPosition"))
{
finalFormula = tempFormulaFibonacci.Replace("numberPosition", Convert.ToString(Array.IndexOf(Sequence, Sequence[Convert.ToInt32(addPrevSlider.Value)]) - 1));
}
});
I decided to automatically create formulas in one of my programs. This code that you see above was meant to find "numberPosition" in the formula and replace it with some numbers (don't pay much attention to the names of the variables since they don't particularly matter in the context of this question).
The main problem that I was having with this code is the fact that it was not working correctly. If I deleted one if
statement and everything that was inside of it, the code would work half-correctly. If I leave both if
statements with everything that is inside of them, the code just would not work right, so I decided to use async
and await
to solve the problem (maybe the problem was there I figured, possibly the Replace
method is taking a bit long). However, when I tried to run the code that you see above, I started getting InvalidOperationException
"The calling thread cannot access this object because a different thread owns it". I have found this solution from The calling thread cannot access this object because a different thread owns it, however:
this.Dispatcher.Invoke(() =>
{
...// your code here.
});
This solution would not be an asynchronous method. How can I turn the code above into an asynchronous method?