I am able to achieve this without threads and its working fine except that it is taking much time in a foreach loop. So, I would like to add threads to this.
I would be hard-pressed to be convinced that “adding threads to” such an algorithm that is right now “working fine(!)” will actually make it either more reliable, or faster. Threading always divides time, while adding considerable complication. So, all kinds of Danger, Will Robinson! alarm bells are going off in my head. What is the procedure that is being performed by this loop that is taking too much time? What is the source of the delay?
Don’t “diddle” code to make it faster: find a better algorithm.
– Kernighan and Plauger; The Elements of Programming Style.