C#.NET - 使用后台线程但GUI没有响应

时间:2017-03-20 07:42:16

标签: c# .net

我正在实施一个客户,他可以向某个服务询问某个操作,也可以执行此操作的中止按钮。 一旦我使用后台线程运行操作,中止按钮应该变为活动状态,但是整个GUI会被鼠标图标作为沙漏(应该提到操作仍然确实发生)。

    private void actionButton_Click(object sender, EventArgs e)
    {
        Run(RunMode.Action);
    }

    private void Run(RunMode runMode)
    {
        abortButton.Enabled = true;
        try
        {
            var name = "ds_file";
            var url = UrlProvider.BuildRequestUrl(runMode, name);

            StartLoading($"Running request: {url}");

            RunWorker(url);
        }
        catch (Exception ex)
        {
            AddToLog(ex.ToString());
            PopError("Failed to run, see error in log box");
        }

    }

    private void RunWorker(string url)
    {
        var worker = new BackgroundWorker();
        worker.DoWork += (sender, args) =>
        {
            DatabaseHelper.DisableAllJobs();
            HttpRequestsHandler.HttpGet(url);
            DatabaseHelper.EnableRegularJobs();
        };
        worker.RunWorkerCompleted += (sender, args) =>
        {
            StopLoading();
            abortButton.Enabled = false;
            if (args.Error != null)
            {
                PopError("Failed to run, see error in log box");
                AddToLog(args.Error.ToString());
            }
            else
            {
                PopInfo("Completed successfully");
            }
        };
        worker.RunWorkerAsync();
    }

我做错了什么?

由于

2 个答案:

答案 0 :(得分:2)

以下示例每10秒运行后台服务以更新GUI。您可以根据需要进行修改。通过将线程作为异步任务运行,您的GUI永远不会挂起。

public frm_testform()
    {

        InitializeComponent();

        dispatcherTimer_Tick().DoNotAwait();

    }

private async Task dispatcherTimer_Tick()
    {
        DispatcherTimer timer = new DispatcherTimer();
        TaskCompletionSource<bool> tcs = null;
        EventHandler tickHandler = (s, e) => tcs.TrySetResult(true);

        timer.Interval = TimeSpan.FromSeconds(10);
        timer.Tick += tickHandler;
        timer.Start();

        while (true)
        {
            tcs = new TaskCompletionSource<bool>();

            await Task.Run(() =>
            {
           // Run your background service and UI update here
            await tcs.Task;
        }

    }

答案 1 :(得分:0)

事实证明我在代码的某些部分有control.enable = false(我真的认为它完全是为了别的东西),谢谢大家的帮助!!