Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么这段代码只在第二次运行时起作用?_C#_Wpf_Winforms_Async Await_Bing Maps - Fatal编程技术网

C# 为什么这段代码只在第二次运行时起作用?

C# 为什么这段代码只在第二次运行时起作用?,c#,wpf,winforms,async-await,bing-maps,C#,Wpf,Winforms,Async Await,Bing Maps,在我的mapping应用程序中,当我用一个位置的所有数据填充一个表时,除了坐标(纬度和经度)——我不希望用户知道/提供坐标——这些值将在以后第一次将数据表示的地图加载到应用程序中时以编程方式确定 当我从主窗体加载现有地图时,代码如下: private void loadExistingMapToolStripMenuItem_Click(object sender, EventArgs e) { bool pushpinsAdded = false; RemoveCurrentP

在我的mapping应用程序中,当我用一个位置的所有数据填充一个表时,除了坐标(纬度和经度)——我不希望用户知道/提供坐标——这些值将在以后第一次将数据表示的地图加载到应用程序中时以编程方式确定

当我从主窗体加载现有地图时,代码如下:

private void loadExistingMapToolStripMenuItem_Click(object sender, EventArgs e)
{
    bool pushpinsAdded = false;
    RemoveCurrentPushpins();
    using (var frmLoadExistingMap = new mdlDlgFrm_LoadExistingMap())
    {
        if (frmLoadExistingMap.ShowDialog() == DialogResult.OK)
        {
            foreach (Pushpin pin in frmLoadExistingMap.Pins)
            {
                this.userControl11.myMap.Children.Add(pin);
                pushpinsAdded = true;
            }
        }
    }
    if (pushpinsAdded)
    {
        RightsizeZoomLevelForAllPushpins();
    }
    lblMapName.Text = currentMap;
    lblMapName.Visible = true;
}
“加载现有映射”表单(frmLoadExistingMap)中的代码确定地址的坐标。如果坐标已经存在,很好;否则,将进行REST调用以获取这些值:

private async void AddPushpinToListOfPushpins(string location, string fullAddress, string mapDetailNotes, double latitude, double longitude, string pushpinColor)
{
    iContentCounter = iContentCounter + 1;
    string toolTip = string.Empty;
    // if already have the record, including the coordinates, no need to make the REST call
    if ((latitude != 0.0) && (longitude != 0.0))
    {
        if (mapDetailNotesExist(location))
        {
            toolTip = String.Format("{0}{1}{2}{1}{3},{4}{1}{5}", location, Environment.NewLine, fullAddress, latitude, longitude, mapDetailNotes.Trim());
        }
        else
        {
            toolTip = String.Format("{0}{1}{2}{1}{3},{4}", location, Environment.NewLine, fullAddress, latitude, longitude);
        }
        var _mapLocation = new Microsoft.Maps.MapControl.WPF.Location(latitude, longitude);
        this.Pins.Add(new Pushpin()
        {
            Location = _mapLocation,
            ToolTip = toolTip,
            Content = iContentCounter,
            Background = new SolidColorBrush(GetColorForDesc(pushpinColor))
        });
    }
    else
    {
        // from https://stackoverflow.com/questions/65752688/how-can-i-retrieve-latitude-and-longitude-of-a-postal-address-using-bing-maps
        var request = new GeocodeRequest();
        request.BingMapsKey = "heavens2MurgatroidAndSufferinSuccotash";
        request.Query = fullAddress;

        var result = await request.Execute();
        if (result.StatusCode == 200)
        {
            var toolkitLocation = (result?.ResourceSets?.FirstOrDefault())
                    ?.Resources?.FirstOrDefault()
                    as BingMapsRESTToolkit.Location;
            var _latitude = toolkitLocation.Point.Coordinates[0];
            var _longitude = toolkitLocation.Point.Coordinates[1];
            var mapLocation = new Microsoft.Maps.MapControl.WPF.Location(_latitude, _longitude);                
            this.Pins.Add(new Pushpin() 
            { 
                Location = mapLocation,
                ToolTip = String.Format("{0}{1}{2}{1}{3},{4}{1}{5}", location, Environment.NewLine, fullAddress, _latitude, _longitude, mapDetailNotes),
                Content = iContentCounter,
                Background = new SolidColorBrush(GetColorForDesc(pushpinColor))
            });
            UpdateLocationWithCoordinates(location, _latitude, _longitude);
        }
    }
}
当到达正上方代码中的“else”块时(当数据库中尚不存在坐标时),不会第一次添加图钉。但是,如果我立即再次运行相同的代码,它就会工作——即使不停止并重新启动应用程序

我知道这个问题与异步代码有关,但是为什么它(到目前为止)第一次不起作用,但(到目前为止)总是第二次起作用

更重要的是,我有没有办法让它在第一次工作时就起作用

更新 对于Reza Aghaei:

private void UpdateLocationWithCoordinates(string location, double latitude, double longitude)
{ 
    String query = "UPDATE CartographerDetail " +
                   "SET Latitude = @Latitude, " +
                   "Longitude = @Longitude " +
                   "WHERE FKMapName = @FKMapName AND LocationName = @LocationName";
    try
    {
        var con = new SqliteConnection(connStr);
        con.Open();

        SqliteCommand cmd = new SqliteCommand(query, con);
        // FKMapName and LocationName are for the WHERE clause
        cmd.Parameters.AddWithValue("@FKMapName", mapName);
        cmd.Parameters.AddWithValue("@LocationName", location);
        // Updated values
        cmd.Parameters.AddWithValue("@Latitude", latitude);
        cmd.Parameters.AddWithValue("@Longitude", longitude);
        cmd.ExecuteNonQuery();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}
以下是“加载现有地图”表单:

其“加载选定地图”按钮单击可执行以下操作:

private void btnLoadSelectedMap_Click(object sender, EventArgs e)
{
    string latitudeAsStr = string.Empty;
    string longitudeAsStr = string.Empty;
    List<MapDetails> lstMapDetails = new List<MapDetails>();
    MapDetails md;
    . . . 
    try
    {
        Form1.currentMap = mapName; 
        string qry = "SELECT LocationName, Address1, Address2, City, StateOrSo, PostalCode, " +
                        "MapDetailNotes, Latitude, Longitude " +
                        "FROM CartographerDetail " +
                        "WHERE FKMapName = @FKMapName";
        var con = new SqliteConnection(connStr);
        con.Open();
        SqliteCommand cmd = new SqliteCommand(qry, con);
        cmd.Parameters.AddWithValue("@FKMapName", mapName);
        var reader = cmd.ExecuteReader();
        while (reader.Read())
        {
            md = new MapDetails();
            md.LocationName = reader.GetValue(LOC_NAME).ToString().Trim();
           . . .
            latitudeAsStr = reader.GetValue(LATITUDE).ToString();
            if (string.IsNullOrEmpty(latitudeAsStr))
            {
                md.Latitude = 0.0;
            }
            else
            {
                md.Latitude = Convert.ToDouble(reader.GetValue(LATITUDE).ToString());
            }
            longitudeAsStr = reader.GetValue(LONGITUDE).ToString();
            if (string.IsNullOrEmpty(longitudeAsStr))
            {
                md.Longitude = 0.0;
            }
            else
            {
                md.Longitude = Convert.ToDouble(reader.GetValue(LONGITUDE).ToString());
            }
            lstMapDetails.Add(md);
        }
        AddPushpinsToListOfPushpins(lstMapDetails);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    // All pushpins have been loaded
    this.Close();
}
另外,AddPushpinsToListOfPushpins()代码(在循环中调用addPushPintToListofPushPins())是:

private void AddPushpinsToListOfPushpins(List<MapDetails> lstMapDetails)
{
    string fullAddress;

    foreach (MapDetails _md in lstMapDetails)
    {
        fullAddress = string.Format("{0} {1} {2} {3}", _md.Address, _md.City, _md.StateOrSo, _md.PostalCode).Trim();
        AddPushpinToListOfPushpins(_md.LocationName, fullAddress, _md.MapDetailNotes, _md.Latitude, _md.Longitude, _md.PushpinColor);
    }
}
private void AddPushpinsToListOfPushpins(列表lstMapDetails)
{
字符串完整地址;
foreach(地图详细信息_md在lstMapDetails中)
{
fullAddress=string.Format(“{0}{1}{2}{3}”,_md.Address,_md.City,_md.StateOrSo,_md.PostalCode).Trim();
添加PushPintToListofPushPins(_md.LocationName,fullAddress,_md.MapDetailNotes,_md.Latitude,_md.Latitude,_md.PushpinColor);
}
}

在添加图钉之前,是否需要设置/更新位置坐标? 如果不能调试这个,很难说。但感觉就像用坐标(位置、纬度、经度)运行UpdateLocation;方法调用在添加PIN之前,它将第一次为您工作。
我的想法是,该方法调用在第一次运行的addpins部分之后运行。这就是为什么在第二次运行时,每次“到目前为止”都会成功运行并添加插针的原因。

在添加插针之前,是否需要设置/更新位置坐标? 如果不能调试这个,很难说。但感觉就像用坐标(位置、纬度、经度)运行UpdateLocation;方法调用在添加PIN之前,它将第一次为您工作。
我的想法是,该方法调用在第一次运行的addpins部分之后运行。这就是为什么它在第二次运行时成功地运行并添加了管脚,每次“到目前为止”。据我所见,代码中的主要问题是调用
async
方法而不使用
wait
操作符。在使用异步/等待:

时请考虑以下几点
  • async void
    适用于事件处理程序,但不适用于需要在代码中直接调用的方法

    更改:

    private async void AddPushpinToListOfPushpins(string location, string fullAddress, string mapDetailNotes, double latitude, double longitude, string pushpinColor)
    
    AddPushpinToListOfPushpins(_md.LocationName, fullAddress, _md.MapDetailNotes, _md.Latitude, _md.Longitude, _md.PushpinColor);
    
    private void AddPushpinsToListOfPushpins(List<MapDetails> lstMapDetails)
    
    致:

  • 当您想要调用返回
    Task
    Task
    的方法时,您需要使用
    wait
    操作符

    更改:

    private async void AddPushpinToListOfPushpins(string location, string fullAddress, string mapDetailNotes, double latitude, double longitude, string pushpinColor)
    
    AddPushpinToListOfPushpins(_md.LocationName, fullAddress, _md.MapDetailNotes, _md.Latitude, _md.Longitude, _md.PushpinColor);
    
    private void AddPushpinsToListOfPushpins(List<MapDetails> lstMapDetails)
    
    致:

  • 当需要使用
    wait
    运算符时,包含该行代码的方法应声明为
    async
    ,并且该方法的返回类型应从
    void
    更改为
    Task
    (或从
    T
    更改为
    Task
    )。(唯一的例外是事件处理程序,将它们更改为
    async void

    更改:

    private async void AddPushpinToListOfPushpins(string location, string fullAddress, string mapDetailNotes, double latitude, double longitude, string pushpinColor)
    
    AddPushpinToListOfPushpins(_md.LocationName, fullAddress, _md.MapDetailNotes, _md.Latitude, _md.Longitude, _md.PushpinColor);
    
    private void AddPushpinsToListOfPushpins(List<MapDetails> lstMapDetails)
    
    致:

  • 关于第三点(也是第一点)中提到的内容,更改:

  • 其他一些要点(与问题无关,但需要解决):

    • 要关闭对话框时,只需设置对话框结果,以便在
      btnLoadSelectedMap\u中单击
      ,将
      this.close()
      替换为
      this.DialogResult=DialogResult.OK,则您不需要
      mdlDlgFrm\u LoadExistingMap\u FormClosed

    • 当您打开一个连接时,您有责任关闭它,以便任何
      con.open()应通过
      con.Close()耦合当您不再需要连接时


    据我所知,代码中的主要问题是调用
    async
    方法而不使用
    wait
    操作符。在使用异步/等待:

    时请考虑以下几点
  • async void
    适用于事件处理程序,但不适用于需要在代码中直接调用的方法

    更改:

    private async void AddPushpinToListOfPushpins(string location, string fullAddress, string mapDetailNotes, double latitude, double longitude, string pushpinColor)
    
    AddPushpinToListOfPushpins(_md.LocationName, fullAddress, _md.MapDetailNotes, _md.Latitude, _md.Longitude, _md.PushpinColor);
    
    private void AddPushpinsToListOfPushpins(List<MapDetails> lstMapDetails)
    
    致:

  • 当您想要调用返回
    Task
    Task
    的方法时,您需要使用
    wait
    操作符

    更改:

    private async void AddPushpinToListOfPushpins(string location, string fullAddress, string mapDetailNotes, double latitude, double longitude, string pushpinColor)
    
    AddPushpinToListOfPushpins(_md.LocationName, fullAddress, _md.MapDetailNotes, _md.Latitude, _md.Longitude, _md.PushpinColor);
    
    private void AddPushpinsToListOfPushpins(List<MapDetails> lstMapDetails)
    
    致:

  • 当需要使用
    wait
    运算符时,包含该行代码的方法应声明为
    async
    ,并且该方法的返回类型应从
    void
    更改为
    Task
    (或从
    T
    更改为
    Task
    )。(唯一的例外是事件处理程序,将它们更改为
    async void

    更改:

    private async void AddPushpinToListOfPushpins(string location, string fullAddress, string mapDetailNotes, double latitude, double longitude, string pushpinColor)
    
    AddPushpinToListOfPushpins(_md.LocationName, fullAddress, _md.MapDetailNotes, _md.Latitude, _md.Longitude, _md.PushpinColor);
    
    private void AddPushpinsToListOfPushpins(List<MapDetails> lstMapDetails)
    
    致:

  • 关于第三点(也是第一点)中提到的内容,更改:

  • 其他一些要点(与问题无关,但需要解决):

    • 要关闭对话框时,只需设置对话框结果,以便在
      btnLoadSelectedMap\u中单击
      ,将
      this.close()
      替换为
      this.DialogResult=DialogResult.OK,则您不需要
      mdlDlgFrm\u LoadExistingMap\u FormClosed

    • 当您打开一个连接时,您有责任关闭它,以便任何
      con.open()应通过
      con.Close()耦合当您不再需要接头时