3

I'm a beginner in programming and I've read several tutorials. I'm still unclear about the following:

When clicking on a button, that event creates an instance of a class:

private void button2_Click(object sender, RoutedEventArgs e)
{
    int a = 1;
    myClass test = new myClass(a);
}

myClass is doing a long processing job (several minutes). If I click 5 times on my button, is it gonna create 5 instances? Or is the "test" going to be "overwritten" 4 times?

Thanks

2
  • Below, are two very good answers to a good beginner question -- its important to note that if the constructor of myClass is synchronous, you will be blocking on your UI thread for quite some time. Commented Apr 23, 2011 at 19:38
  • 1
    Just to add - if you didn#t want to create additional objects in this case, in the event of the user being over zealous with their clicking, you can always disable the button once clicked using Button.Enabled = false; Commented Apr 23, 2011 at 20:47

2 Answers 2

8

If I click 5 times on my button, is it gonna create 5 instances ? Or the "test" instance will be "overwritten" 4 times ?

Yes its going to create 5 separate instances. You are creating an object that immediately falls out of scope after it is constructed, so the next time a different instance of the same class is constructed.

I assume you were planning to do the processing as part of your constructor, keep in mind this will block the UI thread, your program will "freeze" - if you are looking to do a long processing job, you shouldn't do it on the UI thread - look into i.e. the BackgroundWorker.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. Where should I use the BackgroundWorker ? Not inside the class I guess, but rather in the button function ?
@snipef: You can make the BackgroundWorker a variable on your form, then you can use it directly in the button click handler, provided you also add the additional DoWork() and WorkCompleted() (if needed) methods.
3

It will create however many instances that you click. However, if the work is synchronous and blocks the UI thread you can't click it again until the work has completed. If your work is asynchronous it will create a new instance every time you click.

Instead try...

private myClass _test;
private void button2_Click(object sender, RoutedEventArgs e)
{
    int a = 1;

    if (_test == null)
    {
        _test = new myClass(a);
    }
}

Though, I would not recommend doing synchronous work on the UI thread.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.