SHRI
SHRI

Reputation: 2466

thread for method with return value in C#

Delay.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace LearnThread
{
    class Delay
    {
        public int Convert()
        {
            int ErrorCode = 1;
            //something
            //takes long time. about 9 hours.
            return ErrorCode;
        }
    }
}

Form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace LearnThread
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            Delay delay = new Delay();
            Thread t = new Thread(delay.Convert);
            //something
            MessageBox.Show("Success");
        }
    }
}

Delay delay = new Delay(); is error here as it is expecting return value. I want the return value as it is contains errorcode. How can I do that? Background worker is better than Thread? Please help. (I should not lose control on the form when delay.Convert() is running.)

Upvotes: 0

Views: 5228

Answers (2)

Manoj
Manoj

Reputation: 5087

As mentioned by Juergen, you can make ErrorCode a class member and then access it once the thread has completed execution. This would require you to create a new instance of the Delay class if you are trying to run multiple Convert in parallel.

You can also use a delegate to get the return value to a variable in the btnStart_Click function as follows:

private void button1_Click(object sender, EventArgs e)
        {
            Delay delay = new Delay();
            int delayResult = 0;
            Thread t = new Thread(delegate() { delayResult = delay.Convert(); });
            t.Start();
            while (t.IsAlive)
            {
                System.Threading.Thread.Sleep(500);
            }
            MessageBox.Show(delayResult.ToString()); 
        }

If you plan to run Convert in parallel here, you would have to create as many local variable as required or handle it someother way.

Upvotes: 4

juergen d
juergen d

Reputation: 204766

Make the ErrorCode a class member. This way you can get it afterwards.

class Delay
{
    public int ErrorCode { get; private set; }
    public void Convert()
    {
        ErrorCode = 1;
        ...
    }
}


private void btnStart_Click(object sender, EventArgs e)
{
    Delay delay = new Delay();
    Thread t = new Thread(delay.Convert);
    //something
    int error = delay.ErrorCode;
    MessageBox.Show("Success");
}

Upvotes: 2

Related Questions