0

If I created a delegate to allow multiple parameters to be passed into the thread start method, as described in this answer, what would be the best way to return a value from the RealStart method to the method which starts the thread?

As I see it, my options are either to create a static variable.

private static Boolean result;
private static String message = "";

public Thread StartTheThread(SomeType param1, SomeOtherType param2) {
  var t = new Thread(() => RealStart(param1, param2));
  t.Start();
  return t;
}

private static void RealStart(SomeType param1, SomeOtherType param2) {
  ...
}

or to wrap the the delegate in a class

private class TestThread
{
    public String message = "";
    public Boolean result;

    public Thread StartTheThread(SomeType param1, SomeOtherType param2) {
      var t = new Thread(() => RealStart(param1, param2));
      t.Start();
      return t;
    }

    private static void RealStart(SomeType param1, SomeOtherType param2) {
      ...
    }
}

One issue I see with using a class is that it somewhat negates the point of passing parameters via the delegate as I could pass them into the class when I initialize it.

(Or the third option of not using it in this manner) Could RealStart ever have a return type?

Are there any pros or cons to using either of the processes described, even if it just comes down to structure/organisation of code?

Community
  • 1
  • 1
Amicable
  • 3,115
  • 3
  • 49
  • 77

2 Answers2

2

Use Task, and Task.Result:

    // Return a value type with a lambda expression
    Task<int> task1 = Task<int>.Factory.StartNew(() => 1);
    int i = task1.Result;

    // Return a named reference type with a multi-line statement lambda.
    Task<Test> task2 = Task<Test>.Factory.StartNew(() =>
    {
        string s = ".NET";
        double d = 4.0;
        return new Test { Name = s, Number = d };
    });
    Test test = task2.Result;
David
  • 15,894
  • 22
  • 55
  • 66
1

You can use Actions too (for updating form components...):

public TextBox foo = new TextBox();
foo.Text = "foo";
.
.
.
Thread t = new Thread(() => FooBar(p1, p2) );
t.Start();

public void FooBar(Parm parm1, Parm parm2)
{
    ...
    this.foo.BeginInvoke(new Action(() => foo.Text = "bar"));
}
cezarlamann
  • 1,465
  • 2
  • 28
  • 43