[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 277
  • Last Modified:

Delegates, returning values to main form

i'm stuck and can't find solution. I'm a novice in C#...

I have two files in my project...this is just a simplified example, my real app is more complicated :)
1. Main FORM that has a textbox and a Button on it.
2. and annother file "CLASS" that has defined a function that generates random values (for example).

now... On a click of a button I create a thread that calls function form that class file like this.

Class1 delaj = new Class1();
Thread t = new Thread(new ThreadStart(delaj.GenerateNumbers));
t.Start();

...here is my problem. How can I pass generated value back to main form, each time that is generated, so that I can append generated value in my textbox? I know how to create event handler so that I can trigger an event each time that number is generated. I can't figure it out how to get that geneated value.
0
gruntar
Asked:
gruntar
1 Solution
 
AlexFMCommented:
Take a look at this article, it is close to your case. It passes strings, replace strings with numbers.

http://www.codeguru.com/Csharp/Csharp/cs_syntax/article.php/c5851/

Changes:

public delegate void DelegateNumber(int n);
...

public class MainForm : System.Windows.Forms.Form
{
    public DelegateNumber m_DelegateNumber;
    ...

    m_DelegateNumber = new DelegateNumber(this.AddNumber);
    ...

    private void AddNumber(int n)
    {
      // add number to textbox here
    }
}

Thread code (assuming that m_form is reference to the form):

int n = 5;   // some number

m_form.Invoke(m_form.m_DelegateNumber, new Object[] {n});

or:

m_form.BeginInvoke(m_form.m_DelegateNumber, new Object[] {n});
0
 
Bob LearnedCommented:
Why don't you create a static function so that you don't need an instantiated class to retrieve a random number?  It would be like String.Format, Array.Sort, etc.

Bob
0
 
gruntarAuthor Commented:
TheLearnedOne, can you give me an example for my case?
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now