开发者

C# setting tab causes freeze [closed]

Closed. This question is off-topic. It is not currently accepting answers.
开发者_如何学Go

Want to improve this question? Update the question so it's on-topic for Stack Overflow.

Closed 11 years ago.

Improve this question

Whenever I set the selected tab

tcTabs.SelectedTab = secondTab;

The entire application freezes without any error messages. How can I fix this?

Some code

    private void downloadThread()
    {
        WebClient wc;


        wc = new WebClient();

        lbStatus.Text = "Creating directory";
        System.IO.Directory.CreateDirectory("C:\\Program Files\\foo");

        pbMain.Value = 33;
        Thread.Sleep(1000);

        lbStatus.Text = "Downloading files";
        wc.DownloadFile("http://website.net/foo.exe", "C:\\Program Files\\foo\\foo.exe");

        Thread.Sleep(1000);
        pbMain.Value = 66;

        lbStatus.Text = "Creating shortcuts";
        appShortcutToDesktop("C:\\Program Files\\foo\\foo.exe", "foo");

        pbMain.Value = 100;
        Thread.Sleep(1000);

        tcMain.Width = 186;
        tcMain.Height = 122;
        this.Width = 186;
        this.Height = 122;

        tcMain.SelectedTab = tpName;

        while (tcMain.SelectedTab != tpAddWebsites)
            Thread.Sleep(1000);

        tcMain.Width = 218;
        tcMain.Height = 147;
        this.Width = 218;
        this.Height =  147;
    }

Picture of the application after the selectedtab is set to tpName http://segnosis.net/screenshots/b1ktn5.png


If you're switching tabs in a thread, you need to use Form.Invoke:

void SetSecondTab()
{
    tcTabs.SelectedTab = secondTab;
}

void SwitchTabsFromThread()
{
    this.Invoke(new Action(() => { SetSecondTab(); }));
}


Since you seem to be insistent on seeing an answer that uses a delegate then you could (if your downloadThread code is in your Form) just do something like this at each location that you are touching the UI:

BeginInvoke((MethodInvoker)( () => lbStatus.Text = "Creating directory"; ));


Your main problem is that you are accessing UI elements from what I assume (based on the method name alone) is a non-UI thread. You simply cannot do this. You cannot do anything with any UI form or control from a thread other than the main UI thread; the only exception being the ISynchronizeInvoke methods. You are going to have to reconsider how the application is architected and make some significant changes. The freezing issue is just one, albiet visible, symptom of a broader problem.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜