在按钮单击后在后台进行api调用并立即移动到另一个视图

时间:2017-12-12 19:45:27

标签: xamarin xamarin.ios

我有一个保存按钮,当我点击它时,我想进行api调用并移动到另一个视图。由于api调用需要一段时间才能完成,所以我想在单击按钮并在后台进行api调用后立即转到下一个视图。我无法做到这一点。这是我的按钮touchupinside事件中的代码:

InvokeInBackground(MakeApiCall);
var storyBoard = UIStoryboard.FromName("Main", NSBundle.MainBundle);
MainTabBarController viewController = storyBoard.InstantiateViewController("MainTabBarController") as MainTabBarController;
PresentViewController(viewController, true, null);

1 个答案:

答案 0 :(得分:2)

使用Grand Central Dispatch(GCD)在后台队列/线程上放置Action

DispatchQueue.GetGlobalQueue(DispatchQueuePriority.Background).DispatchAsync(() =>
{
    SomeFunctionToRunOnQueue();
});

实施例

public override void ViewDidLoad()
{
    base.ViewDidLoad();

    button = new UIButton(new CGRect(50, 50, 200, 50))
    {
        BackgroundColor = UIColor.Red
    };
    button.SetTitle("Background", UIControlState.Normal);
    Add(button);
    button.TouchUpInside += (object sender, EventArgs e) =>
    {
        Console.WriteLine($"Current Thread: {Thread.CurrentThread.ManagedThreadId}");
        DispatchQueue.GetGlobalQueue(DispatchQueuePriority.Background).DispatchAsync(() =>
        {
            DoWork();
        });
    };
}

public async void DoWork()
{
    Console.WriteLine($"Current Thread: {Thread.CurrentThread.ManagedThreadId}");

    // Do some work...
    await Task.Delay(2000);

    // Go back to the UI thread to do some display updates
    DispatchQueue.MainQueue.DispatchAsync(() =>
    {
        Console.WriteLine($"Current Thread: {Thread.CurrentThread.ManagedThreadId}");
        button.BackgroundColor = UIColor.Green;
    });
}