2

I need to abort a thread if the code takes more than 3 seconds to execute. I am using the below method.

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);
}

Can you please tell how can I do the same thing for the function having parameters. For example:

public static Double LongRunningOperation(int a,int b) {
}
H H
  • 263,252
  • 30
  • 330
  • 514
sharmila
  • 1,493
  • 5
  • 23
  • 42
  • This might give you a clue? Thread Constructor (ParameterizedThreadStart) http://msdn.microsoft.com/en-us/library/1h2f2459.aspx – Hauns TM Jul 13 '12 at 06:17
  • A side note: Thread.Abort() is considered unsafe, it could destabilize or deadlock your app. Depending on what LongRunningOperation() is executing. – H H Jul 13 '12 at 06:38

2 Answers2

0

See ParameterizedThreadStart

If you are using .Net>=4.0 You can also use TPL

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

--EDIT--

Per your edit(answer)

Change your code as below

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

and

public static void LongRunningOperation(object ao){.....}
L.B
  • 114,136
  • 19
  • 178
  • 224
0

You need to create a class that'll contain the 2 int parameters and then use ParametrizedThreadStart and pass in your object

Fedor Hajdu
  • 4,657
  • 3
  • 32
  • 50