0

Tests

I have a function f1(string, string) which takes 4 seconds to execute (irrelevant what it does). Tested this by calling f1("a", "b") in main.

Calling

Console.WriteLine(f1("a", "b")); 
Console.WriteLine(f1("a", "b")); 

will wait 4 seconds for the first function to finish, prompt the return, wait another 4 seconds, prompt the second result all fine and dandy.

I've tried doing this in parallel by creating two separate anonymous threads with lambda like so:

new Thread(() => {Console.WriteLine(f1("a", "b")); }).Start();
new Thread(() => {Console.WriteLine(f1("a", "b")); }).Start();

Since I have a dual core processor and the functions are processing heavy (OS balanced this out very well) I have gotten both prompts after 4 seconds (instead of 8) so I know it worked in parallel.

Question

How can I write a function f1Async(string, string) which would initially call f1(string, string) albeit on a different thread every time (like I've done manually in main)? In order to know what the output of f1Async will be I have to wait for the thread to finish thus calling f1Async() two times in a row will result in the function waiting for one thread to finish before moving on to the second call.

2
  • Whoa, hold on there, before you venture off in the land of multithreading, you better know the basics first... Get a book, find a tutorial, or something, you're not going to get far without it. Commented Mar 7, 2016 at 23:53
  • Can you be more specific? I don't see anything terribly wrong with the question in and on itself. Commented Mar 8, 2016 at 0:03

1 Answer 1

1

I think you're looking for Parallel.For. It will run multiple iterations of an action in parallel, and will wait for all iterations to finish.

If you want to run your f1 two times asynchronously before continuing:

Parallel.For(0, 2, i => Console.WriteLine(f1("a", "b")));

Keep in mind that asynchronous data output may result in jumbled data. You should probably lock your Console.WriteLine for thread safety:

object synchro = new object();
Parallel.For(0, 2, i =>
{
    var output = f1("a", "b");
    lock (synchro)
    {
        Console.WriteLine(output);
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Elegant, clear and simply brilliant answer. I didn't even know about the existance of such thing like Parallel.For. The problem I posted was vastly simplified but I felt like I just missed some mechanic to sort things out. Thanks, well earned upvote :)!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.