Just pass in the BackgroundWorker
to the GetPermutations
method as a parameter. Something along these lines.
using System.ComponentModel;
namespace PersonComp
{
internal class Program
{
static void Main()
{
TestPerms();
Console.ReadLine();
}
public static void TestPerms()
{
BackgroundWorker? backgroundWorker = new()
{
WorkerReportsProgress = true,
WorkerSupportsCancellation = true
};
backgroundWorker.DoWork += BackgroundWorkerDoWork;
backgroundWorker.ProgressChanged += BackgroundWorkerProgressChanged;
IEnumerable <int > index = [1, 2, 3];
var perms = GetPermutations(index, 3, backgroundWorker);
foreach (var perm in perms)
{
Thread.Sleep(200);
Console.WriteLine(string.Join(',', perm));
}
Console.ReadLine();
}
private static void BackgroundWorkerDoWork(object? sender, DoWorkEventArgs e)
{
BackgroundWorker? worker = sender as BackgroundWorker;
for (int i = 1; i <= 10; i++)
{
if (worker!.CancellationPending == true)
{
e.Cancel = true;
break;
}
else
{
Thread.Sleep(10);
worker.ReportProgress(i * 10);
}
}
}
private static void BackgroundWorkerProgressChanged(object? sender, ProgressChangedEventArgs e)
{
Console.WriteLine(e.ProgressPercentage.ToString() + "%");
}
private static IEnumerable <IEnumerable <int > > GetPermutations(IEnumerable <int > fromArray,
int chooseN,
BackgroundWorker backgroundWorker)
{
if (chooseN == 1)
{
foreach (var index in fromArray)
{
yield return new[] { index };
}
yield break;
}
var indicesList = fromArray.ToList();
var subPermutations = GetPermutations(indicesList, chooseN - 1, backgroundWorker);
foreach (var index in indicesList)
{
foreach (IEnumerable <int > subPerm in subPermutations)
{
if (!subPerm.Contains(index))
{
yield return subPerm.Append(index);
if (backgroundWorker.IsBusy is false)
{
backgroundWorker.RunWorkerAsync();
}
}
}
}
}
}
}