---
title: "Creating a task inside a foreach loop"  
description: "Creating a task inside a foreach loop"  
author: "Anonymous User"  
published: 2014-08-14  
updated: 2014-08-14  
canonical: https://www.mindstick.com/forum/2037/creating-a-task-inside-a-foreach-loop  
category: "c#"  
tags: ["c#"]  
reading_time: 1 minute  

---

# Creating a task inside a foreach loop

I have a typical [foreach loop](https://www.mindstick.com/forum/182/problem-in-getting-the-value-from-array-by-using-foreach-loop) that calls a [method](https://www.mindstick.com/forum/166/webservice-method) where the [parameter](https://www.mindstick.com/blog/450/parameter-class-in-c-sharp) is an element of the [collection](https://www.mindstick.com/articles/1718/collections-in-java) we're looping over; something like this:

```
foreach (byte x in SomeCollection){   SomeMethod(x);}
```

The [problem](https://yourviews.mindstick.com/view/81399/tackling-the-problem-of-unemployment-during-corona-pandemic) is that SomeMethod takes a [long](https://www.mindstick.com/articles/44565/white-wedding-dresses-long-prom-dresses) time to run. I want to move the call into a new task so that the loop just creates the [tasks](https://www.mindstick.com/forum/12789/i-want-to-restore-a-database-bak-file-tasks-restore-database-after-i-select-from-device-and-select-file) and then the thread that called the [loops](https://www.mindstick.com/forum/161927/explain-the-python-while-loops-with-example) just continues. How do I do this in a thread-[safe](https://www.mindstick.com/articles/126322/how-to-keep-your-home-safe-while-traveling) way?

Thanks.

## Replies

### Reply by Pravesh Singh

hi Jeet, You can try this:

[foreach](https://www.mindstick.com/forum/33870/how-parallel-foreach-works-internally) (byte x in SomeCollection) { Task.Factory.StartNew(() => SomeMethod(x)); }


---

Original Source: https://www.mindstick.com/forum/2037/creating-a-task-inside-a-foreach-loop

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
