locked
How can run multiple threads in cross-platform? RRS feed

  • Question

  • User146025 posted

    I am developing a forms app with Xamarin Studio on mac and I want to execute some task in parallel but in shared code I cannot access neither Parallel.ForEach neither Thread.

    Any idea?

    Wednesday, December 2, 2015 11:34 AM

Answers

  • User60104 posted

    Try using Tasks from System.Threading.Tasks. You usually use tasks in the xamarin app environment for parallel and asynchronous scenarious. Tasks don't spawn new threads necessarily but enable you to execute code asynchronous and parallel anyway. Have a look here for general information about asynchronous tasks.

    A possible solution for your parallel foreach requirement with tasks: Assuming you have some enumerable named items you could do something like this

                var tasks = new List<Task>();
    
                foreach (var item in items)
                {
                    tasks.Add(new Task(() =>
                    {
                        // do something with the item in this action
                    }));
                }
    
                await Task.WhenAll(tasks);
    

    This will start a new action encapsulated in a task for each item in items and waits asynchronous for every task to finish. Of course, you still have to take care of error handling and stuff, but this could be a way to solve it.

    • Marked as answer by Anonymous Thursday, June 3, 2021 12:00 AM
    Thursday, December 10, 2015 9:56 AM