开发者

C# Class instance

I'm a beginner in programming and I've read several tu开发者_运维技巧torials. 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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜