简体   繁体   中英

Abort ado.net query

I am implementing a autocomplete control. Every time the user types a new character into a input, a query will fire. In order to test I have created a large database where the average query takes about 5 seconds to execute.

Because the query takes 5 seconds to execute I execute the query on a new thread:

   // execute the following lamda expression when user enters characters to textbox
   textBox1.TextChanged +=(x,eventArgs)=>{

            // execute query on separate thread
            new Thread(new ThreadStart(() =>
            {
                ObservableCollection = MyEntities.Entities.Products.Where(p => p.Name.Contains(inputText));
            })).Start();
    };

ObservableCollection and inputText are properties binded to my textbox and list.

The problem is that if the user types two characters my program will be running two threads at the same time. How can I abort the query?


Things that I am thinking about:

Create a bool variable IsQueryRuning and set it equal to true quen query starts and equal to false when thread ends. If a new query will be executed and IsQueryRuning = true then I can set ObservableCollection =null and cause an exeption. I will then resove it with a try catch block. I think that technique is not the best approach..


Edit:

Setting property Collection=null sometimes causes an exception and some other times it does not...

I would suggest a different approach, if that is possible to change for you.

Instead of querying on each keystroke of the user, I would only do a query after, for example, 3 characters. Keep the result in some collection in memory.

After that, only do the next queries on the in-memory collection. That spares you any following database accesses that are always much slower and ou should get a considerable performance gain.

class Program
{        
    public class Person
    {
        public string Name;
        public int Age;
    }        

    public static void ExecuteQueryAsync ( IEnumerable<Person> collectionToQuery , Action<List<Person>> onQueryTerminated , out Action stopExecutionOfQuery )
    {
        var abort = false;

        stopExecutionOfQuery = () =>
        {
            abort = true;
        };            

        Task.Factory.StartNew( () =>
        {
            try
            {
                var query = collectionToQuery.Where( x =>
                {
                    if ( abort )
                        throw new NotImplementedException( "Query aborted" );

                    // query logic:
                    if ( x.Age < 25 )
                        return true;
                    return
                        false;
                } );

                onQueryTerminated( query.ToList() );

            }
            catch
            {
                onQueryTerminated( null );
            }
        });
    }


    static void Main ( string[] args )
    {
        Random random = new Random();

        Person[] people = new Person[ 1000000 ];

        // populate array
        for ( var i = 0 ; i < people.Length ; i++ )
            people[ i ] = new Person() { Age = random.Next( 0 , 100 ) };

        Action abortQuery;
        ExecuteQueryAsync( people , OnQueryDone , out abortQuery );

        // if after some time user wants to stop query:
        abortQuery();

        Console.Read();
    }

    static void OnQueryDone ( List<Person> results )
    {
        if ( results == null )
            Console.WriteLine( "Query was canceled by the user" );
        else
            Console.WriteLine( "Query yield " + results.Count + " results" );
    }
}

I had to execute the query like:

    public IEnumerable<T> ExecuteQuery(IEnumerable<T> query)
    {
        foreach (var t in query)
        {
            if (counterOfSymultaneosQueries > 1)
            {
                // if there are more than two queries break from the last one
                // breaking from it will decrease counterOfSymoltanosQueries
                break;
            }
            yield return t;
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM