解决方法
我创建了这个类,将NetworkActivityIndicatorVisible包装成一对进入/离开方法.
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 ();
然后我像往常一样使用任务.