0

I'm developing that need to use a asynchoronous method. I know my program will not pause to wait the result of that method. But my program must have the result of that method to continue. So, how can I pause my program until I get the result of that method? Otherwise, I need to synchronize a program that contains asynchronous methods.

This is my code:

private async void DiaChiGanNhat()
    {
        double kc;

        Geolocator myGeolocator = new Geolocator();
        Geoposition myGeoposition = await myGeolocator.GetGeopositionAsync();
        Geocoordinate myGeocoordinate = myGeoposition.Coordinate;
        GeoCoordinate myGeoCoordinate = ConvertGeocoordinate(myGeocoordinate);

        IList<DiaChi> dc = dc_control.LocTheoTheLoai(TheLoai(txtTimKiem.Text));
        for (int i = 0; i < dc.Count; i++)
        {
            kc = TinhKhoangCach(myGeoCoordinate.Longitude, myGeoCoordinate.Latitude, dc[i].KinhDo, dc[i].ViDo);
            distance[i] = kc;
        }

        //sap xep tang dan ve khoang cach va ID
        for (int i = 0; i < distance.Length; i++)
        {
            if (distance[i] > distance[i + 1])
            {
                double tg1 = distance[i];
                distance[i] = distance[i + 1];
                distance[i + 1] = tg1;

                int tg2 = id[i];
                id[i] = id[i + 1];
                id[i + 1] = tg2;
            }
        }
    }
private void bttTimKiem_Click(object sender, RoutedEventArgs e)
    {
        DiaChiGanNhat();
        IList<DiaChi> addr1 = dc_control.LocTheoID(id[0]);
        txtDiaChi1.Text = addr1[0].TenDiaChi;

        IList<DiaChi> addr2 = dc_control.LocTheoID(id[1]);
        txtDiaChi2.Text = addr2[0].TenDiaChi;

        IList<DiaChi> addr3 = dc_control.LocTheoID(id[2]);
        txtDiaChi3.Text = addr3[0].TenDiaChi;
    }

That's my problem. I must pause my program until the method DiaChiGanNhat() finish. Don't worry about the method name, cuz I'm Vietnamese. LOL

Thank you so much for helping me!

4

2 回答 2

0

调用函数时使用 await 应该可以工作。

尝试

await DiaChiGanNhat();

请阅读下面的评论。

于 2013-10-27T14:18:06.257 回答
0

您可以使用 a 尝试此操作Wait,它将阻止该方法,直到完成:

private void bttTimKiem_Click(object sender, RoutedEventArgs e)
    {
        var task = Task.Factory.StartNew(DiaChiGanNhat);
        task.Wait();  

        IList<DiaChi> addr1 = dc_control.LocTheoID(id[0]);
        txtDiaChi1.Text = addr1[0].TenDiaChi;

        IList<DiaChi> addr2 = dc_control.LocTheoID(id[1]);
        txtDiaChi2.Text = addr2[0].TenDiaChi;

        IList<DiaChi> addr3 = dc_control.LocTheoID(id[2]);
        txtDiaChi3.Text = addr3[0].TenDiaChi;
    }
于 2013-10-27T04:56:45.657 回答