代码之家  ›  专栏  ›  技术社区  ›  Boardy

在c语言的线程中运行带参数的方法#

c#
  •  16
  • Boardy  · 技术社区  · 15 年前

    我现在在C#工作。我有一个名为updateProgress()的方法,它有两个int参数(count和totalRows)。

    如果我通过说updateProgress(count,totalRows)来调用该方法,那么这很好,但我希望在新线程中运行该方法。

    我怎么能这么做呢?我上网查过了,我想做的事情看起来太复杂了。

    谢谢你的帮助

    6 回复  |  直到 15 年前
        1
  •  31
  •   cdhowie    15 年前

    像这样的:

    new Thread(delegate () {
        updateProgress(count, totalRows);
    }).Start();
    
        2
  •  7
  •   Oliver Hanappi    15 年前

    请注意,线程实际上是一个相当复杂的主题,因此如果您在理解.NET框架中可用的异步API时遇到困难,我怀疑您是否应该首先开始使用线程。

    无论如何,您有几个选择:

    • 用你自己的方法(就像cdhowie指出的那样),这是相当令人沮丧的。

    • 如果在.NET 4上运行,请使用TPL(任务并行库)。 Here 是很好的介绍。 TaskFactory.StartNew(() => updateProgress(count, totalRows));

    • 如果要在较旧版本的.NET上运行,请使用线程池。 ThreadPool.QueueUserWorkItem(s => updateProgress(count, totalRows));

    当然也有其他方法,但这是国际海事组织最重要的方法。

    谨致问候,
    奥利弗·哈纳比

        3
  •  4
  •   Arghya C    10 年前

    这已经快一年了,我的回答不会增加任何内容 “新的” 对于其他答案中已经说过的话。

    如果有人在使用.Net 4.0或更高版本,最好的选择是使用一个任务,让框架通过调用 TaskFactory.StartNew(...) . 对于较旧的版本,使用 ThreadPool.QueueUserWorkItem(...) .

    现在,如果仍有人出于某种原因希望以基本方式(创建新线程)使用线程,那么

    new Thread(delegate () {
        updateProgress(count, totalRows);
    }).Start();
    

    可以使用lambda表达式以更简洁的方式编写,如下所示

    new Thread(() => updateProgress(count, totalRows)).Start();
    
        4
  •  1
  •   svick Raja Nadar    15 年前

    有不同的方法可以在不同的线程中运行方法,比如 Thread , BackgroundWorker , ThreadPool Task . 选择哪一个取决于各种各样的事情。

    从方法的名称来看,听起来该方法应该在应用程序的GUI中显示一些进展。如果是这样,你 不得不 在GUI线程上运行该方法。如果你想从另一个线程调用它,你必须使用 Dispatcher.Invoke() 在WPF和 Control.Invoke() 在WinForms中。

        5
  •  0
  •   Zain Shaikh    15 年前

    尝试跟随

    ThreadPool.QueueUserWorkItem((o) => { updateProgress(5, 6); });
    
        6
  •  0
  •   rboarman    15 年前

    下面是一个没有匿名委托的更复杂的例子。在完成的函数中查看结果。

    using System;
    using System.Threading;
    using System.ComponentModel;
    
    class Program
    {
      static BackgroundWorker _bw;
    
      static void Main()
      {
        _bw = new BackgroundWorker
        {
          WorkerReportsProgress = true,
          WorkerSupportsCancellation = true
        };
        _bw.DoWork += bw_DoWork;
        _bw.ProgressChanged += bw_ProgressChanged;
        _bw.RunWorkerCompleted += bw_RunWorkerCompleted;
    
        _bw.RunWorkerAsync ("Hello to worker");
    
        Console.WriteLine ("Press Enter in the next 5 seconds to cancel");
        Console.ReadLine();
        if (_bw.IsBusy) _bw.CancelAsync();
        Console.ReadLine();
      }
    
      static void bw_DoWork (object sender, DoWorkEventArgs e)
      {
        for (int i = 0; i <= 100; i += 20)
        {
          if (_bw.CancellationPending) { e.Cancel = true; return; }
          _bw.ReportProgress (i);
          Thread.Sleep (1000);      // Just for the demo... don't go sleeping
        }                           // for real in pooled threads!
    
        e.Result = 123;    // This gets passed to RunWorkerCompleted
      }
    
      static void bw_RunWorkerCompleted (object sender,
                                         RunWorkerCompletedEventArgs e)
      {
        if (e.Cancelled)
          Console.WriteLine ("You canceled!");
        else if (e.Error != null)
          Console.WriteLine ("Worker exception: " + e.Error.ToString());
        else
          Console.WriteLine ("Complete: " + e.Result);      // from DoWork
      }
    
      static void bw_ProgressChanged (object sender,
                                      ProgressChangedEventArgs e)
      {
        Console.WriteLine ("Reached " + e.ProgressPercentage + "%");
      }
    }