Use synchronous or asynchronous tasks to collect print counters

1

I'm trying to develop a process that performs the collection of some printer counters via SNMP protocol, I thought about using Threads to perform this process, I refaced to use tasks, but I do not know if I should use an async await for this task, in this case I get a little confused if I'm developing this method in the best way. Here is the method code:

private void timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        using (ImpressoraDAO dao = new ImpressoraDAO())
        {
            var impressoras = dao.Listar().ToList();
            var impressorasTasks = impressoras.Select(impressora =>
            {
                return Task.Factory.StartNew(() =>
                {
                    if (impressora.IsConected())
                    {
                        using (ContadorDAO contadorDao = new ContadorDAO())
                        {
                            var contador = new Contador();
                            contador.Id = DateTime.Now;
                            contador.ImpressoraId = impressora.Id;
                            contador.QuantidadePaginas = Convert.ToInt64(OperacaoSNMP.ObterObjetoOID(IPAddress.Parse(impressora.Ip), OID.CONTADADOR_TOTAL));
                            contadorDao.Adicionar(contador);
                        }
                    }
                });
            }).ToArray();

            Task.WhenAll(impressorasTasks);
        }
    }

How can I improve this code? Should I leave it like this or would it be better to use an async await?

    
asked by anonymous 27.09.2017 / 14:27

1 answer

0

In this case it may be best not to use Task . Tasks work best when you have% asynchronous% operations. Because while I\O is not processed the CPU can continue to do other things.

One thing I noticed is that the I\O method might be poorly implemented. I do not know what this method does. But if he makes a query in the database then it would make sense for him to be asynchronous. And then you should use tasks.

A better approach to the current code would be to use contadorDao.Adicionar(contador)

var impressoras = dao.Listar().ToList();
Parallel.ForEach(impressoras, impressora => {
    if (impressora.IsConected())
    {
        using (ContadorDAO contadorDao = new ContadorDAO())
        {
            var contador = new Contador();
            contador.Id = DateTime.Now;
            contador.ImpressoraId = impressora.Id;
            contador.QuantidadePaginas = Convert.ToInt64(OperacaoSNMP.ObterObjetoOID(IPAddress.Parse(impressora.Ip), OID.CONTADADOR_TOTAL));
            contadorDao.Adicionar(contador);
        }
    }
});

In the latter case you will have to resort to profilling techniques to see what approach is best for your scenario.

    
27.09.2017 / 14:57