Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# .NET在X秒数后引发异常/引发事件_C#_.net - Fatal编程技术网

C# .NET在X秒数后引发异常/引发事件

C# .NET在X秒数后引发异常/引发事件,c#,.net,C#,.net,在长时间运行的C#方法中,我希望在经过数秒后抛出异常或引发事件 这可能吗?您可以通过使用计时器来完成此操作-将其设置为您希望的超时,并在方法开始时启动 在方法的最后,禁用计时器-只有在计时器超时时才会触发,并且您可以连接到滴答事件 var timer = new Timer(timeout); timer.Elapsed = ElapsedEventHanler; // Name of the event handler timer.Start(); // do long running pr

在长时间运行的C#方法中,我希望在经过数秒后抛出异常或引发事件


这可能吗?

您可以通过使用计时器来完成此操作-将其设置为您希望的超时,并在方法开始时启动

在方法的最后,禁用计时器-只有在计时器超时时才会触发,并且您可以连接到滴答事件

var timer = new Timer(timeout);
timer.Elapsed = ElapsedEventHanler; // Name of the event handler
timer.Start();

// do long running process

timer.Stop();

我建议阅读-这将让您知道其中哪一个最适合您的特殊需要。

使用System.Threading.Timer:

System.Threading.Timer t;
int seconds = 0;

public void start() {

    TimerCallback tcb = new TimerCallback(tick);
    t = new System.Threading.Timer(tcb);
    t.Change(0, 1000);          
}

public void tick(object o)
{
    seconds++;
    if (seconds == 60)
    {
        // do something
    }
}

如果您打算停止长时间运行的方法,那么我认为向该方法添加取消支持将是一种更好的方法,而不是引发异常。

尝试以下方法,它具有取消异常(如果进程完成)的功能,并在源线程上引发异常:

var targetThreadDispatcher = Dispatcher.CurrentDispatcher;
var tokenSource = new CancellationTokenSource();
var cancellationToken = tokenSource.Token;
Task.Factory.StartNew(() => 
{
    var ct = cancellationToken;

    // How long the process has to run
    Task.Delay(TimeSpan.FromSeconds(5));

    // Exit the thread if the process completed
    ct.ThrowIfCancellationRequest();

    // Throw exception to target thread
    targetThreadDispatcher.Invoke(() => 
    {
        throw new MyExceptionClass();
    }
}, cancellationToken);

RunProcess();

// Cancel the exception raising if the process was completed.
tokenSource.Cancel();

您是否尝试过使用
计时器
?我只能认为,异常不会在您的方法运行的线程上引发。@ Habib,您是否认为异常会出现在不同的线程上,因此该方法最有可能继续吗?不像我认为的那么简单?@LukeHennerley,OP可以引发一个事件或timer-appeased事件,该事件可以在其他地方被捕获,timer可以调用一个句点上的方法。但是,这就回避了线程的问题。所以,也许真正的问题是“谁在乎”。如果我们知道谁在乎这种方法需要很长时间,那么我们可以给出更好的答案。