1

Using the answer about the lambda operator from here, I've got a thread that accepts parameters and works fine. However I'd like to be able to get stuff back from the thread. This is what the code looks like:

namespace Renamer
{
    class RenameThread
    {
        public Thread StartRename(bool commit, ICollection checkeditems, ArrayList rules)
        {
            var t = new Thread(() => doRename(commit, checkeditems, rules));
            t.Start();
            return t;

        }
        private void doRename(bool commit, ICollection checkeditems, ArrayList rules)
        {
            ArrayList filenames = new ArrayList();
            ArrayList newfilenames = new ArrayList();
            filenames.AddRange(checkeditems);
            //do stuff with filenames
            //I want to be able to return newfilenames (or perhaps some object that contains it)
        }
    }
}

It gets called from clicking on a button:

private void btnTest_Click(object sender, EventArgs e)
{
    RenameThread rt = new RenameThread();
    Thread renameThread = rt.StartRename(false, clbFiles.CheckedItems, rules);
    renameThread.Join();
}

In Java I'd just implement Runnable so I could get direct access to the thread's members and fields if I needed them, but since I can't inherit from Thread I'm at a bit of a loss as to what I should do.

Community
  • 1
  • 1
ldam
  • 4,412
  • 6
  • 45
  • 76

1 Answers1

2

You would use Tasks:

var renameTask = Task.Factory.StartNew(() => Rename(...));

You can now wait for the task to finish, similar to your Join, by accessing Result:

var newFilenames = renameTask.Result;

Or you could do that asynchronous:

renameTask.ContinueWith(t => Console.WriteLine(t.Result));

My answer assumes that Rename is a method that returns a string.

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443