I have the following exercise to do(no real life example):
Implement a search method that uses a number of threads provided from user to find all letter of a list that start with a string.
My solution:
public async void Search(string filterString, int numberOfThreads)
{
int count = _listOfStrings.Count;
IEnumerable<IEnumerable<string>> lists = SplitList(_wrapper.Words, count / numberOfThreads);
IEnumerable<string>[] results = await Task.WhenAll(lists.Select(list => FilterList(list, filterString)));
List<string> temp = new List<string>();
foreach (var item in results.ToList())
{
temp.AddRange(item);
}
Results = new ObservableCollection<string>(temp);
}
public IEnumerable<IEnumerable<string>> SplitList(IEnumerable<string> source, int chunksize)
{
while (source.Any())
{
yield return source.Take(chunksize);
source = source.Skip(chunksize);
}
}
private async Task<IEnumerable<string>> FilterList(IEnumerable<string> list, string filterString)
{
var filteredList = await Task.Run(() => list.Where(x => x.StartsWith(filterString)));
return filteredList;
}
Is this a method that runs on mutiple threads or is something blocking the main thread?
For the second part I need to replace the thread functionality with win32 API Methods.
I tried for starters something like this :
public async void Search(string filterString, int numberOfThreads)
{
var lists = SplitList(_listOfStrings, numberOfThreads);
foreach (var list in lists)
{
FilterDelegate filterDelegate = (list, filterString) =>
{
return FilterList(list, filterString);
};
IntPtr filterPtr = Marshal.GetFunctionPointerForDelegate(filterDelegate);
int handle = CreateThread(IntPtr.Zero, 0, filterPtr, IntPtr.Zero, 0, 0);
}
}
[DllImport("kernel32")]
private static extern int CreateThread(
IntPtr lpThreadAttributes, UInt32 dwStackSize, IntPtr lpStartAddress,
IntPtr param, UInt32 dwCreationFlags, UInt32 lpThreadId
);
private delegate Task<IEnumerable<string>> FilterDelegate(IEnumerable<string> list, string filter);
But I do not know how to continue. How is it possible to change the Thread functionality with a WIN32 API implementation?