简体   繁体   English

C#应用程序不是交互式的,而循环在后面运行

[英]C# Application is not intertactive while a loop runs in back

I have made an application in c# vs 2010 .net 4.0. 我已经在c#vs 2010 .net 4.0中进行了应用。 It gets rss feed from gmail and then shows them in a simple table. 它从gmail获取rss feed,然后在一个简单的表格中显示它们。 But the problem start when i use a timer to check updates in string rss from a 40 sec time. 但是,当我使用计时器从40秒的时间检查字符串rss中的更新时,问题就开始了。 The program works fine but it becomes unresponsive i cannot click a button or anything. 该程序工作正常,但变得无响应,我无法单击按钮或任何东西。 I Need help. 我需要帮助。 Note My App has to be operational after a task started. 注意任务开始后,我的应用程序必须可运行。

Yes. 是。 Your application is doing its work on the UI thread without interacting with the Windows event loop. 您的应用程序正在UI线程上完成其工作,而没有与Windows事件循环进行交互。 You need to do your work on a background thread (perhaps using BackgroundWorker ). 您需要在后台线程上进行工作(也许使用BackgroundWorker )。

Here is a very simple example using BackgroundWorker in a WinForms applcation (but do check the class documentation linked to above): 这是一个在WinForms应用程序中使用BackgroundWorker的非常简单的示例(但请检查上面链接的类文档):

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        var bw = new BackgroundWorker();
        bw.DoWork += new DoWorkEventHandler(bw_DoWork);
        bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
        bw.RunWorkerAsync();
    }

    // update UI back on main thread
    void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        listBox1.Items.AddRange(content.ToArray());
    }

    List<string> content;

    // do work on background thread
    void bw_DoWork(object sender, DoWorkEventArgs e)
    {
        content = new List<string>();
        // simulate slow update
        for (int i = 0; i < 1000; i++)
        {
            Thread.Sleep(10);
            content.Add(i.ToString());
        }
    }
}

我会研究异步方法来下载,例如WebClient.DownloadStringAsync

Background worker or async web clients are the way to go. 后台工作者或异步Web客户端是必经之路。 I would just like to add that I found strange behavior when I last used a webclient. 我只想补充一点,我上次使用Web客户端时发现了奇怪的行为。 Every first call I would make from a webclient object would result in about a 30-40 second wait, until the data was retrieved. 我从webclient对象发出的每个首次调用将导致大约30-40秒的等待,直到检索到数据为止。 Subsequent calls would be much faster. 随后的通话会更快。 It ended up being something to do with the webclients default proxy setting, setting the proxy to null would eliminate the wait. 最终与webclients默认代理设置有关,将代理设置为null可以消除等待。

Setting the proxy to null would probably not be the best solution, just mentioning it in case it leads you to a better solution. 将代理设置为null可能不是最好的解决方案,只是提及它以防您导致更好的解决方案。

Do not use a background thread for this. 请勿为此使用后台线程。 Async != new thread. 异步!=新线程。 If you use a new thread to do synchronous web requests you'll (very quickly) starve the thread pool (Assuming you're using background workers). 如果您使用新线程来执行同步Web请求,您将(很快)使线程池饿死(假设您正在使用后台工作程序)。

A single thread can manage hundreds of asynchronous web requests but only one synchronous request at any one time. 一个线程可以管理数百个异步Web请求,但一次只能管理一个同步请求。

If you're a beginner I highly recommend following CodeInChaos's advice and using a WebClient. 如果您是初学者,我强烈建议您遵循CodeInChaos的建议并使用WebClient。 The upside of a WebClient is it takes care of all the asynchronous plumbing for you. WebClient的好处是可以为您处理所有异步管道。 The downside is that because it does everything for you you lose a lot of control over the webrequest (Ie Can't modify http headers etc.) and it also returns the result on the UI thread (Which in your case is actually a positive thing). 缺点是因为它会为您做所有事情,所以您对webrequest失去了很多控制权(例如,无法修改http标头等),并且它还会在UI线程上返回结果(在您的情况下,这实际上是一件好事) )。

var webUri = new Uri("www.website.com");
var webClient = new WebClient();

webClient.DownloadDataCompleted += DownloadDataCallback;
webClient.DownloadStringAsync(webUri, null);

private void DownloadDataCallback (Object sender, DownloadDataCompletedEventArgs e)
{
     var webRequestResult = e.Result;
}

在循环内,在任何地方写以下行

Application.DoEvents()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM