在TPL任务运行时如何显示iOS网络指示器?

在与服务器API交谈时,我大量使用任务并行库.
我想显示iOS网络指示器,而这些任务当前正在运行.

我该怎么做?

解决方法

我创建了这个类,将NetworkActivityIndi​​catorVisible包装成一对进入/离开方法.
public static class NetworkIndicator
{
    static int _counter;

    public static void Enteractivity ()
    {
        Interlocked.Increment (ref _counter);
        Refreshindicator ();
    }

    public static void LeaveActivity ()
    {
        Interlocked.Decrement (ref _counter);
        Refreshindicator ();
    }

    public static void AttachToTask (Task task)
    {
        if (task.IsCanceled || task.IsCanceled || task.IsFaulted)
            return;

        Enteractivity ();
        task.ContinueWith (t => {
            LeaveActivity ();
        });
    }

    static void Refreshindicator ()
    {
        UIApplication.SharedApplication.NetworkActivityIndicatorVisible =
            (_counter > 0);
    }
}

然后我为方便起见添加了两个扩展方法

public static class TaskExtensions
{
    public static Task WithNetworkIndicator (this Task task)
    {
        NetworkIndicator.AttachToTask (task);
        return task;
    }

    public static Task<TResult> WithNetworkIndicator<TResult> (this Task<TResult> task)
    {
        NetworkIndicator.AttachToTask (task);
        return task;
    }
}

我是如何包装它的:

var task = Api.QueryNotifications (AuthManager.CurrentProfile.Id,NotificationType.All,until,cached)
    .WithNetworkIndicator ();

然后我像往常一样使用任务.

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...