none
Task vs async vs backroundworker RRS feed

  • Question

  • Dear all,

    I am actually facing to different optimization path to be implemented in my application. For that i come to of course multithreading (whuich will not speed up a process bu simply not freeze the main Ui). Then for that I have to consider different things like.

    - i need to be informed when a thred is complete in order to process an other step only in that condition

    - I need to be able to cancel some task if needed

    - I need to send some feedback to main ui main needed

    Then I come to confusion by using TASK, await keyword, background worker.

    When to use one instead of an other ?

    regarsd

    Sunday, June 24, 2018 2:18 PM

All replies

  • There is very, very much on this subject to learn and your question is very vague. These forums are designed for getting answers to specific questions.

    Other operating systems often use different terminology for the same thing. Some programmers might insist that "thread" or "task" have specific definitions but generally speaking they do not; see Thread (computing) - Wikipedia. For .Net "task" for the Task Class has a totally specific definition. Internally, the .Net Task Class uses Windows API threads. Also, the BackgroundWorker Class uses threads internally; there is nothing that the BackgroundWorker class does that you can't do using threads, the BackgroundWorker class is just designed to make it easier to do threads in GUI programs. It is the GUI part that we want to get when we use a BackgroundWorker.

    Async and await can be very confusing. One revelation is that they are not multithreading; they are often necessary when threads (multithreading) are created by something else. Quite often the something else is another program, such as Windows.

    This entire subject is vast and can be very confusing so as I said, find tutorials and/or books on the subject.





    Sam Hobbs
    SimpleSamples.Info

    Sunday, June 24, 2018 6:43 PM
  • Pretty much asynchronous programming today is Async based via task while BackGroundWorker components are still an option I would move away from them as there is more control using awaitables.

    A good place to start learning in in the following page on theory and concepts.

    Writing task base is easy once you have the concepts down. For example, the following which allows an app to stay responsive (but no speed gains, just the opposite) while determine if SQL-Server is available.

    Full source

    /// <summary>
    /// Determine if a specific SQL-Server is available
    /// </summary>
    /// <param name="pServerName">Server name to work with</param>
    /// <returns></returns>
    public async Task<bool> SqlServerIsAvailableAsync(string pServerName)
    {
        bool success = false;
                
        try
        {
    
            await Task.Run(() =>
            {
                var sqlDataSourceEnumeratorInstance = SqlDataSourceEnumerator.Instance;
                var dt = sqlDataSourceEnumeratorInstance.GetDataSources();
                if (dt != null)
                {
                    if (dt.Rows.Count > 0)
                    {
                        var row = dt
                            .AsEnumerable()
                            .FirstOrDefault
                                (
                                    dataRow => dataRow.Field<string>("ServerName") == pServerName.ToUpper()
                                );
    
                        success = row != null;
                    }
                    else
                    {
                        success = false;
                    }
                }
            }).ConfigureAwait(false);
    
        }
        catch (Exception ex)
        {
            _hasException = true;
            _exceptionMessage = ex.Message;
        }
    
        return success;
    
    }
    /// <summary>
    /// Determines if a catalog/database exist on a specific instance of SQL-Server
    /// </summary>
    /// <param name="pServer"></param>
    /// <param name="pDatabase"></param>
    /// <returns></returns>
    public async Task<bool> DatabaseExistsAsync(string pServer, string pDatabase)
    {
        bool success = false;
        var testServer = await SqlServerIsAvailableAsync(pServer).ConfigureAwait(false);
        if (!testServer)
        {
            return false;
        }
    
        try
        {
            var connectionString = ("Data Source=" + (pServer + ";Initial Catalog=master;" + 
                                                        "Integrated Security=True;"));
            var commandText = 
                ("select * from master.dbo.sysdatabases where name='" + (pDatabase + "'"));
    
            using (var cn = new SqlConnection { ConnectionString = connectionString })
            {
                using (var cmd = new SqlCommand { Connection = cn, CommandText = commandText })
                {
                    cn.Open();
                    var reader = await cmd.ExecuteReaderAsync().ConfigureAwait(false);
                    success = reader.HasRows;
                }
            }
        }
        catch (Exception e)
        {
            _hasException = true;
            _exceptionMessage = e.Message;
        }
    
        return success;
    
    }

     

    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Sunday, June 24, 2018 7:38 PM
    Moderator
  • I will probably get a bunch of bullying about this but I think that it is more of a matter of an opinion whether async based is better. For one thing, and as I said already, async and await don't create the threads. I think the new way of doing things are unnecessarily complicated. I don't understand why programmers think that adding complication is an improvement. In the end, it is all done using threads. So I am not saying that the alternatives are no good; I am saying that anyone saying that just one way is the only way to do it might be misleading you. Ideally you should learn all the alternatives and I am saying that for this subject do not to ignore alternatives.

    We often must use async and await. I am not saying not to. I won't get into the details and I am definitely  not an expert so it is best to read articles and books on the subject.



    Sam Hobbs
    SimpleSamples.Info

    Sunday, June 24, 2018 7:54 PM