In a user interface I need users to pick a SQL server from all available instances over the network. I use a button for users to click to display the servers. It take about 25 seconds after the button is clicked before you can display the list. I am thinking to get the server list ready when the page is loaded. So when users click on the button the list is already ready. However, it gets stuck before the page is loaded. remoteSqlServers is used for ItemSource.
internal static ObservableCollection<string> remoteSqlServers = GetRemoteSqlServers().Result;
public static async Task<ObservableCollection<string>> GetRemoteSqlServers()
{
var SqlServers = await Task<ObservableCollection<string>>.Run(() =>
{
return new SqlEnumerationHelper().SqlEnumerateRemote();
}).ConfigureAwait(false);
return SqlServers;
}
I changed it to below it doesn't get stuck before it loads but it still takes quite some seconds. It seems the async doens't work and don't know why.
public static ObservableCollection<string> remoteSqlServers = new ObservableCollection<string>();
public GetSqlViewModel()
{
...
remoteSqlServers = GetRemoteSqlServers().Result;
...
}
public static async Task<ObservableCollection<string>> GetRemoteSqlServers()
{
var SqlServers = await Task<ObservableCollection<string>>.Run(() =>
{
return new SqlEnumerationHelper().SqlEnumerateRemote();
}).ConfigureAwait(false);
return SqlServers;
}
Here is SqlEnumerateRemote:
public ObservableCollection<string> SqlEnumerateRemote()
{
ObservableCollection<string> sqlServerNames = new ObservableCollection<string>();
LogHelper.log("SqlEnumerationHelper:SqlEnumerateRemote", "Starting");
try
{
//Make an initial call to the sql browser service to wake it up
using (DataTable sqlSources = SqlDataSourceEnumerator.Instance.GetDataSources())
{
//There are issues with SqlDataSourceEnumerator, that it doesn't always return all sql instances
}
SqlDataSourceEnumerator instance = SqlDataSourceEnumerator.Instance;
System.Data.DataTable dt = instance.GetDataSources();
DataRow[] rows = dt.Select(string.Empty, "ServerName asc");
if (rows.Length > 0)
{
foreach (DataRow dr in rows)
{
string serverName = dr["ServerName"].ToString();
string instanceName = dr["InstanceName"].ToString();
if (instanceName.Length > 0)
serverName += "\\" + instanceName;
sqlServerNames.Add(serverName);
}
}
LogHelper.log("SqlEnumerationHelper:SqlEnumerateRemote", "Ending");
}
catch (Exception e)
{
LogHelper.log("SqlEnumerationHelper:SqlEnumerateRemote", "SqlDataSourceEnumerator.GetDataSources and assoc processing failed" + e.Message);
}
return sqlServerNames;
}