C# - 中止方法的执行,如果它的时间太长运行 [英] c# - abort the execution of a method if its taking too long to run

查看:655
本文介绍了C# - 中止方法的执行,如果它的时间太长运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么能放弃一个方法的执行,如果它的时间太长运行?

How can I abort the execution of a method if its taking too long to run?

例如。

string foo = DoSomethingComplex();

但如果 DoSomethingComplex()花费的时间太长(20秒可以说)。 只需要设置FOO为;

but if DoSomethingComplex() is taking too long (20 seconds lets say). then just set foo to "";

推荐答案

您可以创建一个新的线程中运行你的方法,那么:

You can create a new thread running your method, then:

thread.Start();
bool success = thread.Join(20000);

连接返回true,如果线程成功完成之前指定的时间。显然,不会中止的方法(可能是没有办法做到的的直接),但是线程 - 但似乎会完成你想要的是什么。

Join returns true if thread finished successfully before designated time. Obviously, would not abort the method (probably no way to do that directly), but the thread -- but it seems that would accomplish what you desired.

一个简单的线程code例如可能会去像下面。请注意我做了一些假设有关的签名与参数,这一切都在一些类等。方法:

A simple threading code example probably would go something like below. Note I made some assumptions about signature with parameter, all this in some class, etc. For method:

    public string DoSomethingComplex(int param)

,然后在同一个类:

and then in the same class:

public delegate void Callback(string newFoo);

public void ThreadedDoSomethingComplexEnded(string newFoo)
{
    foo = newFoo;
}

private static void ThreadedDoSomethingComplex(ClassFooIsIn fooObject, int param, Callback callback)
{
    var newFoo = fooObject.DoSomethingComplex(param);
    callback(newFoo);
}

使用又名code在ClassFooIsIn其他方法:

usage aka code in some other method in ClassFooIsIn:

var thread = new Thread(() => ThreadedDoSomethingComplex(this, param, ThreadedDoSomethingComplexEnded));
thread.Start();

if (!thread.Join(20000))
{
     foo = "";
}

美孚应该如上图所示,使用前进行初始化,所以在现实中你可能跳过富=;行了。

Foo should be initialized before above shown usage, so in reality you could possibly skip foo = ""; line.

这篇关于C# - 中止方法的执行,如果它的时间太长运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆