异步System.Threading.Timer有时会引发null异常 [英] Async System.Threading.Timer sometimes throwing null exception

查看:47
本文介绍了异步System.Threading.Timer有时会引发null异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在一定时间间隔后异步执行代码,并且仅在完成代码执行以防止重叠之后才想再次检查.为此,我使用了以下变量和计时器代码.

I am trying to execute a code asynchronously after a certain interval of time and want to check again only after I am done with the code execution to prevent overlapping. For that I am using the following variables and timer code.

private System.Threading.Timer _timer;
private int _intervalInMilliSec = 10000;

_timer = new System.Threading.Timer(async (o) =>
{
    // Stop the timer;
    _timer.Change(-1, -1);

    // awaited api call goes here

    // start timer again (BeginTime, Interval)
    _timer.Change(_intervalInMilliSec, _intervalInMilliSec);
}, null, 0, _intervalInMilliSec);

大多数情况下它运行良好,但有时我很少在 _timer.Change(-1,-1);

Most of the times it is working fine but sometimes rarely I started getting the following exception at the line _timer.Change(-1, -1);

对象引用未设置为对象的实例

此时,"o"显示为空.请让我知道我在做什么错.谢谢

At that point "o" is showing as null. Please let me know what I am doing wrong. Thanks

推荐答案

我不知道为什么在代码中会出现 NullReferenceException ,但是我建议您删除 Timer 方法,并用一个更简单的 Task.Delay 循环:

I don't know why you get the NullReferenceException in your code, but I suggest to scrap the Timer approach altogether and replace it with a simpler Task.Delay in a loop:

var apiCallCts = new CancellationTokenSource();
var apiCallTask = Task.Run(async () =>
{
    while (true)
    {
        var delayTask = Task.Delay(TimeSpan.FromSeconds(10), apiCallCts.Token);
        await SomeApiCallAsync();
        await delayTask;
    }
});

在应用程序关闭时:

apiCallCts.Cancel();

在API失败的情况下,上述解决方案具有不同的行为.不会崩溃的应用程序,将无声地停止调用API.这是您必须考虑的事情.

The above solution has a different behavior in case of an API failure. Instead of crashing the app, will silently stop calling the API. This is something that you'll have to consider.

这篇关于异步System.Threading.Timer有时会引发null异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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