iOS/Objective-C equivalent of Android's AsyncTask

前端 未结 5 1663
野的像风
野的像风 2020-12-07 09:07

I\'m familiar with using AsyncTask in Android: create a subclass, call execute on an instance of the subclass and onPostExecute is cal

5条回答
  •  隐瞒了意图╮
    2020-12-07 10:00

    Here is a c# Xamarin.iOS version with PusblishProgress:

    internal abstract class AsyncTask : NSObject
    {
        protected abstract nint DoInBackground(NSArray parameters);
    
        protected abstract void PostExecute(nint result);
    
        public void ExecuteParameters(NSArray @params)
        {
            this.PreExecute();
    
            DispatchQueue.GetGlobalQueue(DispatchQueuePriority.Default).DispatchAsync(() =>
            {
                //We're on a Background thread
                var result = this.DoInBackground(@params);
                DispatchQueue.MainQueue.DispatchAsync(() => {
                    // We're on the main thread
                    this.PostExecute(result);
                });
            });
    
        }
    
        protected abstract void PreExecute();
    
        protected void PublishProgress(NSArray parameters)
        {
            InvokeOnMainThread(() => {
                // We're on the main thread
                this.OnProgressUpdate(parameters);
            });
        }
    
        protected abstract void OnProgressUpdate(NSArray parameters);
    }
    

    And implementation:

    internal class MyAsyncTask : AsyncTask
    {
        protected override void OnProgressUpdate(NSArray parameters)
        {
            // This runs on the UI Thread
        }
    
        protected override nint DoInBackground(NSArray parameters)
        {
            // Do some background work
            // ....
            var progress = NSArray.FromObjects(1, "Done step 1");
            PublishProgress(progress);
    
            return 0;
         }
    
         protected override void PostExecute(nint result)
         {
             // This runs on the UI Thread
    
         }
    
         protected override void PreExecute()
         {
            // This runs on the UI Thread
    
         }
    }
    

提交回复
热议问题