Thanh Nguyen
Thanh Nguyen

Reputation: 83

How to use function in other class c#

i have app with guienter image description here

I put function checkproxy() in Form1.cs it works correctly and i want move function checkproxy() to other class but if i put checkproxy() in other class it will error with Invoke and richTextBox3

namespace test3
{
public partial class Form1 : Form
{
    public bool continueThreads = false;
    string[] proxyList = null;
    List<Thread> threadList = new List<Thread>();
    int proxynum = 0;
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
            int n = (int)numericUpDown1.Value;
            Thread[] tl = new Thread[n + 1];
            threadList = tl.ToList();
            for (int i = 0; i <= n; i++)
            {
                threadList[i] = new Thread(new ThreadStart(checkproxy));
            }
            for (int i = 0; i <= n; i++)
            {
                threadList[i].Start();
            }
            continueThreads = true;
            proxyList = richTextBox1.Lines;
    }
    public void checkproxy()
    {
        while (continueThreads)
        {

            if (proxynum >= proxyList.Length)
            {
                continueThreads = false;
            }
            if (proxynum < proxyList.Length)
            {
                string proxy = proxyList[proxynum];
                proxynum += 1;
                string info = "";
                try
                {
                    Thread.Sleep(1000);
                    info += "Live || " + proxy + Environment.NewLine;
                    this.Invoke(new Action(() => richTextBox3.Text += info));
                }
                catch
                {

                }
            }
        }
    }
}
}

this is screenshot error enter image description here

Upvotes: 0

Views: 71

Answers (2)

Tigran
Tigran

Reputation: 62265

Because this is a System.Windows.Forms.Form in original context. To be able to Invoke interface update from another thread/async task, you need to use it (as you did correctly in your original code).

But once you move the function into separate class, there is no more notion of a Conntrol or Form there, so this is a class itself, which does not have Invoke implementation.

One possible solution: you need to refactor your method in a way, that he is able to call Form's function, that internally calls Invoke.

Upvotes: 3

Andrey Korneyev
Andrey Korneyev

Reputation: 26886

Your method checkproxy uses Form1 class members (continueThreads, proxynum and others) directly.

If you really want do move it outside of this class (I'm not sure it is good idea since this method looks very closely related to your class) - you need to refactor this method and pass all class members it uses as method input parameters like

public void checkproxy(bool continueThreads.....)

Upvotes: 3

Related Questions