Итак, у меня есть функция поиска самого длинного пути, которая рекурсивно проходит через некоторый граф. Эта функция должна останавливаться на , ждать до тех пор, пока не будет нажата кнопка «Далее» в форме. Но я не могу понять, как предотвратить возврат функции к предыдущим вызовам самой себя после await :
public async void LongestPath(T current, T from, T to, Stack<Graph<T, W>.Edge> path, W summary)
{
if (EqualityComparer<T>.Default.Equals(current, to)) //if arrived at the end node
{
if (Comparer<W>.Default.Compare(summary, longest) > 0) //if this path is the biggest
{
LongestExists = true;
longest = summary;
longestPath.Clear();
for (int i = 0; i < path.Count; i++)
longestPath.Push(path.ElementAt(i));
}
return;
}
List<Pair<T, Graph<T, W>.Edge>> available = new List<Pair<T, Graph<T, W>.Edge>>(); //current vertice's available routes
for (int i = 0; i < this.Edges.Count; i++)
{
Pair<T, Graph<T, W>.Edge> toAdd = new Pair<T, Graph<T, W>.Edge>();
if (!this.Edges[i].visited)
{
if (this.Edges[i].undirected)
{
if (EqualityComparer<T>.Default.Equals(this.Edges[i].Left, current) && !nodeVisited(this.Edges[i].Left))
{
toAdd.First = this.Edges[i].Right;
toAdd.Second = this.Edges[i];
available.Add(toAdd);
}
else if (EqualityComparer<T>.Default.Equals(this.Edges[i].Right, current) && !nodeVisited(this.Edges[i].Right))
{
toAdd.First = this.Edges[i].Left;
toAdd.Second = this.Edges[i];
available.Add(toAdd);
}
}
else if (EqualityComparer<T>.Default.Equals(this.Edges[i].Left, current) && !nodeVisited(this.Edges[i].Left))
{
toAdd.First = this.Edges[i].Right;
toAdd.Second = this.Edges[i];
available.Add(toAdd);
}
}
}
for (int i = 0; i < available.Count; i++)
{
available.ElementAt(i).Second.visited = true;
path.Push(available.ElementAt(i).Second);
visitNode(current, true); //function that just sets the "visited" flag of a vertice to true
Task check = new Task(() => Form1.CheckNextButtonAsync()); //this task checks the state of "Next" button
check.Start();
await check; //the problem
Form1.NextButtonClicked = false; //function continues from here after the button is clicked but at that moment it had already went back to previous calls of itself
Console.Beep();
LongestPath(available.ElementAt(i).First, from, to, path, GenericSum<W>(summary, available.ElementAt(i).Second.weight));
visitNode(current, false);
available.ElementAt(i).Second.visited = false;
path.Pop();
}
return;
}
Совершенно очевидно, что нерекурсивная функция будет работать идеально. Но есть ли способ «заморозить» нить и сохранить форму работающей, чтобы кнопка могла быть нажата одновременно?