使用的BackgroundWorker /线程时防止GUI变得呆滞C#问题 [英] C# question on preventing GUI from becoming sluggish when using backgroundworker/thread

查看:195
本文介绍了使用的BackgroundWorker /线程时防止GUI变得呆滞C#问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想建立一个小型应用程序登录到服务器并从中不断地收集数据。那我遇到的问题是,我的GUI很慢或者使用后台工作或线程时甚至做出回应。当我的应用程序试图登录到服务器上,我看(无响应)出现在我的登录表单,但它在几秒钟内登录后没有Windows给人以该方案已停止响应...终止应用程序对话框。当我点击我的应用程序启动按钮,我注意到通过GUI变得非常缓慢,反应迟钝。我想知道我怎么能提高我的程序的响应时间。下面是使用一个后台工作和我的线程从服务器收集数据的代码登录窗体的代码。我的代码的最后一节道歉不正确是格式,但SO是被非合作。

 私人无效btnLogin_Click(对象发件人,EventArgs五)
{
如果(string.IsNullOrEmpty(txtAccount.Text)|| string.IsNullOrEmpty(txtPassword.Text))
{
MessageBox.Show(必须输入用户名和密码);
的回报;
}
btnLogin.Enabled = FALSE;
账户= txtAccount.Text;
密码= txtPassword.Text;
ACCOUNTTYPE = cmbAccountType.SelectedItem.ToString();
loginBackgroundWorker.RunWorkerAsync();
}

私人无效loginBackgroundWorker_DoWork(对象发件人,DoWorkEventArgs E)
{
loginSuccess = tradingDesk.Login(账号,密码,ACCOUNTTYPE);
}

私人无效loginBackgroundWorker_RunWorkerCompleted(对象发件人,RunWorkerCompletedEventArgs E)
{
如果(loginSuccess)
{
this.DialogResult =的DialogResult 。好;
}
btnLogin.Enabled = TRUE;
}


私人无效btnStart_Click(对象发件人,EventArgs五)
{
螺纹dataThread =新主题(GetServerData);
dataThread.IsBackground = TRUE;


{
dataThread.Start();
}
赶上(异常前)
{
MessageBox.Show(ex.Message);
}}

私人无效GetServerData()
{

{
,而(真)
{
锁(myLock)

}
}

{$ {
//大量数据
的执行服务器任务} b $ b //处理异常的代码
}
}


解决方案除非你在处理线程的业务正处在一个游泳池和你喜欢的东西(或者你已经做了这样的,因为V1不是自己处理线程更容易 -

尝试使用BackgroundWorker的为您处理。 0,因为我有 - 你只是用这种方式)



我也把我所有的UI交互成为一个后台线程和Marshall调用回通过对UI线程。这篇文章将帮助你在两个:的的更新Windows窗体的工具从后台线程UI



另一个测试是换出你的电话用一个简单的睡眠tradingDesk.Login看如果改变任何东西。怎么是你的CPU?如果发生在CPU使用率的线程或进程尖峰注意到了吗?即使是一个多线程的应用程序,吞噬了所有的CPU将口吃 - 闪存想到 - 减慢我的甚至是整个系统中其它进程


I am trying to build a small application that logins into a server and gathers data from it constantly. The problem that I am having is that my GUI is slow to respond even when using either background worker or a thread. When my application tries to login into the server, I see "(Not Responding)" appear in my login form, but it logins in few seconds later without Windows giving the "The program has stopped responding... terminate application" dialog. When I click the start button on my application I noticed by GUI becomes very sluggish and unresponsive. I was wondering how I could improve the response time of my program. Here is the code for the Login form using a background worker and the code for my thread that gathers data from the server. I apologize for the last section of the code not being format correctly, but SO is being non-cooperative.

    private void btnLogin_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(txtAccount.Text) || string.IsNullOrEmpty(txtPassword.Text))
        {
            MessageBox.Show("Must Enter Username and Password");
            return;
        }
        btnLogin.Enabled = false;
        account = txtAccount.Text;
        password = txtPassword.Text;
        accountType = cmbAccountType.SelectedItem.ToString();
        loginBackgroundWorker.RunWorkerAsync();
    }

    private void loginBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
    {
        loginSuccess=tradingDesk.Login(account, password, accountType);
    }

    private void loginBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        if (loginSuccess)
        {
            this.DialogResult = DialogResult.OK;
        }
        btnLogin.Enabled = true;
    }


    private void btnStart_Click(object sender, EventArgs e)
        {
        Thread dataThread=new Thread(GetServerData);
        dataThread.IsBackground=true;

        try
        {
            dataThread.Start();
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }}

private void GetServerData()
{
    try
    {
        while (true)
        {
            lock (myLock)
            {
               //Perform Server Task with large amounts of data
            }
        }
    }
    catch
    {
        //Handle exception code
    }
}

解决方案

Try using BackgroundWorker for your processing - easier than handling threads yourself unless you're in the business of handling threads in a pool and you like that stuff (or you've been doing it like that since v1.0 as I have - you're just used to it that way).

I also put all my UI interactions into a background thread and marshall the calls back through to the UI thread. This article should help you out on both: Tools for Updating Windows Forms UI from Background Threads

Another test is to swap out your call to tradingDesk.Login with a simple sleep to see if that changes anything. And how's your CPU? Happen to notice if the thread or process spikes in CPU usage? Even a multi-threaded app that eats up all your CPU will stutter - Flash comes to mind - slows down my entire system even other processes.

这篇关于使用的BackgroundWorker /线程时防止GUI变得呆滞C#问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆