tim_po
tim_po

Reputation: 105

Combining Thread with parameters and return value

So i have been multithreading lately,and since im new to this im probably doing something basic wrong..

Thread mainthread = new Thread(() => threadmain("string", "string", "string"));
mainthread.Start();

the above code works flawlessly but now i want to get a value back from my thread. to do that i searched on SO and found this code:

  object value = null; 
  var thread = new Thread(
    () =>
    {
      value = "Hello World"; 
    });
  thread.Start();
  thread.Join();
MessageBox.Show(value);
}

and i dont know how to combine the two.

the return value will be a string.

thank you for helping a newbie,i tried combining them but got errors due to my lack of experience

edit:

my thread:

public void threadmain(string url,string search, string regexstring) {

    using (WebClient client = new WebClient()) // WebClient class inherits IDisposable
    {
        string allthreadusernames = "";
        string htmlCode = client.DownloadString(url);

        string[] htmlarray = htmlCode.Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
        foreach (string line in htmlarray)
        {
            if (line.Contains(search))
            {

                var regex = new Regex(regexstring);
                var matches = regex.Matches(line);
                foreach (var singleuser in matches.Cast<Match>().ToList())
                {
                    allthreadusernames = allthreadusernames + "\n" + singleuser.Groups[1].Value;


                }
            }
        }

        MessageBox.Show(allthreadusernames);

    }

}

Upvotes: 0

Views: 393

Answers (2)

Sebastian Negraszus
Sebastian Negraszus

Reputation: 12215

An easy solution would be to use another level of abstraction for asynchronous operations: Tasks.

Example:

public static int Calculate()
{
  // Simulate some work

  int sum = 0;
  for (int i = 0; i < 10000; i++)
  {
    sum += i;
  }
  return sum;
}

// ...

var task = System.Threading.Tasks.Task.Run(() => Calculate());
int result = task.Result; // waits/blocks until the task is finished

In addition to task.Result, you can also wait for the task with await task (async/await pattern) or task.Wait (+ timeout and/or cancellation token).

Upvotes: 2

Honza Brestan
Honza Brestan

Reputation: 10947

Threads aren't really supposed to behave like functions. The code you found still lacks synchronization/thread-safety of reading/writing the output variable.

Task Parallel Library provides a better abstraction, Tasks.

Your problem can then be solved by code similar to this:

var result = await Task.Run(() => MethodReturningAValue());

Running tasks like this is actually more lightweight, as it only borrows an existing thread from either the SynchronizationContext or the .NET thread pool, with low overhead.

I highly recommend Stephen Cleary's blog series about using tasks for parallelism and asynchronicity. It should answer all your further questions.

Upvotes: 1

Related Questions