简体   繁体   中英

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;

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM