【问题标题】:How to add thread to Winform for button-check如何将线程添加到 Winform 以进行按钮检查
【发布时间】:2014-11-17 10:29:03
【问题描述】:

在 C# 中,我有一个简单的 Winform,当前有一个按钮“开始”,它在点击事件中执行一个功能。此功能大约需要 20 秒。 现在我添加了第二个按钮“停止”,它在点击事件中设置了一个变量“buttonstopclicked = 1”。 在开始按钮的功能中,我检查此变量,如果设置为 1,则退出该功能。

问题是:当 c# 执行启动按钮的事件时,我无法单击停止按钮。

现在的问题是:如何为所有东西添加一个线程来处理按钮?

感谢您的帮助

编辑: 同时我发现了如何创建线程:

    Thread myThread = new Thread(new ThreadStart(ButtonThread));
    myThread.Start();

    private void ButtonThread()
    {
        while (1 != 0)
        {
            if (ButtonStartClicked == 1)
            {
                ButtonStartClicked = 0;
                ExecuteFunction();
            }

            if (ButtonStopClicked == 1)
            {
                ButtonStopClicked = 0;
            }
        }
    }

但现在我在调用函数“ExecuteFunction”中遇到异常。 无效操作异常。

控件是从另一个线程使用/创建的...

我现在可以在这里做什么? 我正在使用 C# 2010 express

【问题讨论】:

  • start 方法需要由一个线程处理,才能让您的 gui 正常响应。这可以通过后台工作人员 msdn.microsoft.com/en-us/library/… 完成
  • 您使用的是什么版本的 .Net/Visual Studio?
  • 我正在使用 Visual C# 2010 express。
  • 这是一个非常低效的编程示例。当您提出问题时,请阅读其他成员发布的 cmets。阅读有关背景工作者的信息,这不是火箭科学。只需几分钟,您就不会像这样弄乱您的代码。

标签: c# multithreading button


【解决方案1】:

按钮在 UI 线程上运行,您正在尝试使用自定义线程与 UI 线程进行交互。对于 UI 中的响应性,您需要使用后台工作人员。创建一个后台工作人员并添加要在其 Do_Work 事件中执行的函数。将以下属性设置为 true(其中 bw 是 backgroundworker 的名称):

bw.WorkerSupportsCancellation = True
bw.WorkerReportsProgress = True

现在,在开始按钮上,您只需在开始按钮的点击事件中添加以下代码即可调用后台工作人员:

If Not bw.IsBusy = True Then
    bw.RunWorkerAsync()
End If

而要取消进程,需要在停止按钮的点击事件中添加如下代码:

If bw.WorkerSupportsCancellation = True Then
    bw.CancelAsync()
End If

通过以下 msdn 链接了解详细信息:http://msdn.microsoft.com/en-us/library/cc221403(v=vs.95).aspx

【讨论】:

    【解决方案2】:

    首先。使用 Thread 并不是最好的方法。 .Net Framework 中有更高级别的抽象。您应该(几乎)始终使用语言提供的最高抽象,并将内部结构留给编译器或运行时,因为它们会做得很好。

    使用 VS 2010,您至少可以访问 TPL(任务并行库 - Introduction)

    要取消任务(在后台使用 ThreadPool 提供的线程),您应该使用 CancellationTokenSource:

    private CancellationTokenSource _ctSource = new CancellationTokenSource();
    

    取消按钮的处理程序然后简单地设置取消令牌:

    private void OnButtonCancelClick(object sender, EventArgs e)
    {
        _ctSource.Cancel();
    }
    

    开始按钮的处理程序可能如下所示:

    private void OnButtonStartClick(object sender, EventArgs e)
    {
        // Start a new task
        Task<int> workerTask = Task<int>.Factory.StartNew(
            () => PerformLongRunningOperation(_ctSource.Token), _ctSource.Token);
    
        // when the task has finished, display the result (On the GUI Thread!)
        workerTask.ContinueWith((task) =>
        {
            if (task.IsCanceled)
            {
                MessageBox.Show("Calculation has been canceled.");
                return;
            }
    
            _LabelResult = task.Result;
        }, TaskScheduler.FromCurrentSynchronizationContext); // required to run this part on the GUI thread
    }
    

    执行实际工作的方法如下所示:

    private int PerformLongRunningOperation(CancellationToken token)
    {
        for (int i = 0; i < 1000000000; i++)
        {
            // will cancel the task if the token has been set
            token.ThrowIfCancellationRequested();
    
            // otherwise do some stuff
        }
    
        return 42;
    }
    

    如果您可以访问 VS2012 和 .NetFramework 4.5 / C# 5.0,使用 async - await,按钮单击处理程序甚至可以简化为如下内容:

    private async void OnButtonStartClick(object sender, EventArgs e)
    {
        try
        {
            // Await will allow the UI to keep responsive
            // Furthermore it will automatically return to the UI SynchronizationContext when done, so updating a label
            // has not to be dispatched.
            _LabelResult = await Task.Factory.StartNew(
                () => PerformLongRunningOperation(_ctSource.Token), _ctSource.Token);
        }
        catch (TaskCanceledException ex)
        {
            MessageBox.Show("Calculation has been canceled.");
        }
    }   
    

    有关使用 C# 进行并行编程的一般介绍,请访问 http://www.albahari.com/threading/part5.aspx#_Parallel_Programming

    请记住,异步会导致您必须考虑的许多其他问题。例如,当您的 UI 具有响应性(应该是什么)时,用户可以一次又一次地点击开始按钮。因此,例如,在您的场景中,您应该考虑禁用按钮,直到任务完成或被取消以避免这种情况。

    【讨论】:

      猜你喜欢
      • 2021-08-18
      • 1970-01-01
      • 2011-10-05
      • 1970-01-01
      • 2017-04-04
      • 1970-01-01
      • 1970-01-01
      • 2011-11-03
      • 2015-07-30
      相关资源
      最近更新 更多