开发者

Getting information back to the main thread from the called thread?

I have a "string" and a "StreamReader" in the main thread. I want to pass these to a thread which will read the streamreader into the string. I want that string to be changed in the main thread. My question is how do I do this?

Additional info: I have specific reasons as to why I want to thread开发者_运维百科 this so please just stick to the specs. Also, I cannot use TPL because I cannot get framework 4.0... Again for specific reasons.


So you make a class with a string and a StreamReader property. You pass in an instance of that class to your other thread using ParameterizedThreadStart. You have that other thread fill that buttercup up by writing to the string property on that instance of your class.

When the thread is done, your string property on the instance of your class will be filled up. Yay.

So something like

 class Foo {
     public string Bar { get; set; }
 }

Then:

 Foo foo = new Foo();
 var thread = new Thread(o => { Foo f = (Foo)o; f.Bar = "FillMeUpButterCup"; });
 thread.Start(foo);
 thread.Join();
 Console.WriteLine(foo);

Wow!

I left off the StreamReader but now you get the point.


When creating the thread you have ParameterizedThreadStart delegate and a parameter that you could pass there. Just create a class with two properties - string and StreamReader (and possibly whatever else you want to pass there) and pass instance of the class into thread starting method.

public class ThreadStartParam
{
    public string Str { get; set; }
    public StreamReader StreamReader { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var t = new Thread(YourMethod);

        var param = new ThreadStartParam();
        param.Str = "abc";
        param.StreamReader = new StreamReader();

        t.Start(param);
    }

    static void YourMethod(object param)
    {
        var p = (ThreadStartParam) param;
        // whatever
    }
}


I wrote a blog post about this sometime last year and I think it'll cover how to properly communicate to a thread and back from a thread. Basically create an object to pass to and from the thread and you can pass to the thread using a ParameterizedThreadStart and you can pass back by having a delegate to invoke.

http://coreyogburn.com/post/Threads-Doing-Them-Right-wGUI.aspx

More specifically in your example of the main thread realizing the changed String that you pass to the thread, I would recommend that on thread completion, you call a method that passes the string value back and re-sets the original string's value. This will prevent the thread from adding to the string while the main thread might try to read it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜