开发者

How to Spawn a parameterised thread which will return a Boolean value in C#?

I am trying to call a method which will return me Boolean values(-1,0,1) by invoking a thread something开发者_运维百科 like:

public void CreateThread()
{
    ThreadStart ts =delegate{check(55);};

    Thread tUpdateNow = new Thread(ts);

    tUpdateNow.Start();

//According to the return value perform some task.
}   
public bool check(int n)
{    
    if(n%2==0)
        return 1;

    else if(n%2>=0)
        return 0;

    else
        return -1;    
}

But I don't know how to implement this using C#. Anybody help me please.


You can use the Task Parallel Library which wraps all this for you.

Task<bool> task = Task<bool>.Factory.StartNew(() => check(55));
bool result = task.Result;


I highly recommend working with BackgroundWorker Class for something like this. You can subscribe to events that will fire when the thread completes. See: BackgroundWorker Events.

Something like:

var bw = new BackgroundWorker();
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);

You can store the result of the DoWork method in the DoWorkEventArgs Result property. When the RunWorkerCompleted event fires, you can retrieve this result from the RunWorkerCompletedEventArgs Result property.


ThreadStart returns void, so in your delegate you are calling your check method and it is throwing away the return value. You will need to store that value somewhere else and then check it once the thread has completed.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜