【问题标题】:Start thread with parameters带参数启动线程
【发布时间】:2012-07-12 23:38:15
【问题描述】:

如果代码执行时间超过 3 秒,我需要中止线程。我正在使用以下方法。

public static void Main(string[] args) {
    if (RunWithTimeout(LongRunningOperation, TimeSpan.FromMilliseconds(3000))) {
        Console.WriteLine("Worker thread finished.");
    } else {
        Console.WriteLine("Worker thread was aborted.");
    }
 }

public static bool RunWithTimeout(ThreadStart threadStart, TimeSpan timeout) {
    Thread workerThread = new Thread(threadStart);
    workerThread.Start();

    bool finished = workerThread.Join(timeout);
    if (!finished)
    workerThread.Abort();

    return finished;
}

public static void LongRunningOperation() {
    Thread.Sleep(5000);
}

你能告诉我如何对有参数的函数做同样的事情吗?例如:

public static Double LongRunningOperation(int a,int b) {
}

【问题讨论】:

  • 这可能会给你一个线索?线程构造函数(ParameterizedThreadStart)msdn.microsoft.com/en-us/library/1h2f2459.aspx
  • 附注:Thread.Abort() 被认为是不安全的,它可能会破坏或死锁您的应用程序。取决于 LongRunningOperation() 正在执行的内容。

标签: c# multithreading parameter-passing abort


【解决方案1】:

ParameterizedThreadStart

如果你使用.Net>=4.0也可以使用TPL

Task.Factory.StartNew(()=>LongRunningOperation(a,b));

--编辑--

根据您的编辑(答案)

如下修改代码

if (RunWithTimeout(new ParameterizedThreadStart(LongRunningOperation), TimeSpan.FromMilliseconds(3000)))

public static void LongRunningOperation(object ao){.....}

【讨论】:

    【解决方案2】:

    您需要创建一个包含 2 个 int 参数的类,然后使用 ParametrizedThreadStart 并传入您的对象

    【讨论】:

      猜你喜欢
      • 2011-07-07
      • 2023-03-13
      • 2011-10-11
      • 2018-09-17
      • 2011-04-24
      • 1970-01-01
      • 2016-01-13
      • 2014-02-03
      • 1970-01-01
      相关资源
      最近更新 更多