通过使用Ping的DataGrid列绑定转换器停止阻塞?

时间:2017-12-01 14:24:02

标签: c# wpf datagrid

我有一个设备列表(Raspberry Pi),我加载到DataGrid。我添加了一个绑定到HostName的DataGridTemplateColumn,并使用转换器获取该HostName,将其ping,并返回红色或绿色位图。我在列绑定上设置了IsAsync = true,因此它现在可以快速加载网格,然后通过列表ping下来。问题是它似乎是阻塞因为窗口没有响应/慢。我甚至尝试过使用带有线程的转换器。我运气不好吗?

XAML

<DataGridTemplateColumn x:Name="Online" Header="Online" IsReadOnly="True" Width="45" >
     <DataGridTemplateColumn.CellTemplate>
         <DataTemplate>
             <Image Height="16" Width="16" Source="{Binding HostName, Converter={StaticResource onlineConverter}, IsAsync=True}" />
         </DataTemplate>
     </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

转换器

public class StatusConverter : IValueConverter
{
    public ImageSource redSource = new BitmapImage(new Uri("pack://application:,,,/PiConsole;component/Resources/red_light.png", UriKind.Absolute));
    public ImageSource greenSource = new BitmapImage(new Uri("pack://application:,,,/PiConsole;component/Resources/green_light.png", UriKind.Absolute));

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        string host = value.ToString().Trim();
        Worker worker = new Worker();
        bool result = false;
        var pingThread = new Thread(() => result = worker.PingDevice(host));
        pingThread.Start();
        pingThread.Join();

        if (result)
        {
            return greenSource;
        }
        else
        {
            return redSource;
        }

    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }

}

public class Worker
{
    public bool PingDevice(string _host)
    {
        Ping ping = new Ping();
        try
        {
            PingReply reply = ping.Send(_host, 100);
            if (reply.Status == IPStatus.Success)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        catch (PingException p)
        {
            //Console.WriteLine(p.InnerException);
        }
        catch (Exception e)
        {
            //Console.WriteLine(e.Message);
        }
        return false;
    }
}

0 个答案:

没有答案