c#BackgroundWorker暂停

时间:2013-10-14 12:37:09

标签: c# backgroundworker

我有一个小的C#应用​​程序,它使用POST方法通过API请求与服务器通信并获取一些数据。顺便说一下,它是一个Apache服务器。

我的问题是我的C#应用​​程序不断发送大量请求,服务器会创建大量日志文件。

我使用BackgroundWorker,我想暂停几秒钟,但Thread.Sleep(5000)无效。

此应用程序在系统托盘中运行,它没有GUI,只是获取一些内容,然后打印出来。

代码:

private void _bgWorker_DoWork(object sender, DoWorkEventArgs e)
    {
        JSONParser parser = new JSONParser(_config.Prop.server + "content/api.php", "print", "getAll");            

        try
        {
            while (!_bgWorker.CancellationPending)
            {
                try
                {
                    JSONPrintNeeds needs = parser.DownloadAll();                        
                    List<JSONPrintNeed> temp = new List<JSONPrintNeed>();

                    foreach (JSONPrintNeed need in needs.data)
                    {
                        temp.Add(need);
                    }

                    foreach (JSONPrintNeed need in temp)
                    {
                        Printer printer = new Printer(need.megrendeles);
                        printer.PrintController = new StandardPrintController();

                        List<String> installed = new List<String>();

                        for (int i = 0; i < PrinterSettings.InstalledPrinters.Count; i++)
                        {
                            installed.Add(PrinterSettings.InstalledPrinters[i]);
                        }

                        if (installed.Contains(need.nyomtato))
                        {
                            printer.PrinterSettings.PrinterName = need.nyomtato;
                        }

                        int format = int.Parse(need.format);

                        switch (format)
                        {
                            case 0: 
                            default:            // txt
                                printer.Print();
                                break;
                            case 1:             // html
                                SetDefaultPrinter(need.nyomtato);
                                browser.DocumentText = need.megrendeles;
                                browser.Print();
                                break;
                        }

                        JSONResult result = parser.DeleteOne(int.Parse(need.ny_id));
                    }

                    parser.DeleteAll();
                    Thread.Sleep(5000);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }

1 个答案:

答案 0 :(得分:0)

您可以将EventWaitHandle用于同步主题。

EventWaitHandle flag = new EventWaitHandle(false, EventResetMode.AutoReset); 
if (stop)
{
    flag.WaitOne(5000);
}