如何设置和调用Async方法

时间:2015-10-29 22:06:14

标签: c# android xamarin async-await visual-studio-2015

我正在使用Mvvm Light开发一个xamarin安卓应用程序,我有一个我正在调用的方法,我想将其更改为异步方法,但我不确定如何。只是好奇如何做到这一点。它适用于Visual Studio中的Xamarin Android应用程序

致电方法:

    protected override void onResume()
    {
         ObservableCollection locObs = Vm.ShowLocations();
    }

方法:

    public ObservableCollection<Location> ShowLocations()
    {
        if (Debugger.IsAttached)
        {
            if (Locations != null)
            {
                var locationsCopy = Locations.ToList();
                Locations = new ObservableCollection<Location>(locationsCopy);
            }
            Election elec = IntentManager.Instance.CurrentElection;
            elec.Locations = new System.Collections.ObjectModel.ObservableCollection<Location>();
            Location loc = new Location();
            loc.Name = "Alan Middle School";
            loc.Address = "300 S. County Farm Road";
            elec.Locations.Add(loc);
            Location loc2 = new Location();
            loc2.Name = "Bill High School";
            loc2.Address = "100 S. County Farm Road";
            elec.Locations.Add(loc2);
            Location loc3 = new Location();
            loc3.Name = "Cameron Fire Station";
            elec.Locations.Add(loc3);
            Location loc4 = new Location();
            loc4.Name = "Danvill Senior Center";
            elec.Locations.Add(loc4);

            Locations = elec.Locations;
        }
        return Locations;
    }

1 个答案:

答案 0 :(得分:1)

  

这将被服务电话取代。这是暂时的我只是要求提供有关Async或示例的提示。

进行服务呼叫后,您可以使用var locations = await GetLocationsAsync(); elec.Locations = new ObservableCollection<Location>(locations); 异步调用它:

async

这要求调用方法为public async Task<ObservableCollection<Location>> ShowLocationsAsync() { var locations = await GetLocationsAsync(); elec.Locations = new ObservableCollection<Location>(locations); return elec.Locations; } ,如下:

protected override async void onResume()
{
  ObservableCollection locObs = await Vm.ShowLocationsAsync();
}

然后可以将其称为:

grep