执行搜索 wpf 时超时

本文关键字:超时 wpf 搜索 执行 | 更新日期: 2023-09-27 17:56:13

当我在应用程序中执行搜索时,我希望有一个超时函数,该函数为用户提供一条消息并在 10 秒后停止搜索。

这怎么可能?你能给我看一下代码吗?

让我知道您是否需要查看我的代码以及您需要查看哪一部分。

谢谢

你好!这是代码。忘了告诉你我使用后台工作者做你发布的建议不起作用。

我想为这件作品设置一个时间限制

private void worker_DoWork(Object sender, DoWorkEventArgs e) { 进度 = 0; 秒表 sw = 新秒表(); 西 南部。开始(); var donewithwork = false;

        while (sw.ElapsedMilliseconds < 5000 && !donewithwork)
        {
            if (m_oWorker.CancellationPending == true)
            {
                e.Cancel = true;
            }
            else if (donewithwork != true)
            {
                                    {
                    try
                    {
                        progress = 10;
                        MongoServerSettings settings = new MongoServerSettings();
                        settings.Server = new MongoServerAddress("lysing.uia.no", 27017);
                        MongoServer server = new MongoServer(settings);
                        MongoDatabase database = server.GetDatabase("tweet_database");
                        var collection = database.GetCollection<Tweets>("docs");
                        var query = Query.And(Query.Matches("text", new BsonRegularExpression(new Regex(searchText, RegexOptions.IgnoreCase)))
                            /*, Query.Near("geo",58.1453, 7.9571, 1000, true)*//*, Query.Matches("created_at", "Jan")*/);

                        var cursor = collection.Find(query);
                        progress = 20;
                        // Sets the cursorLimit to the four same values as the radiobuttons indicates (50,100,500 and 1000)

                        if (cursorLimit != 0)
                        {
                            cursor.SetLimit(cursorLimit);
                        }

                            // If no value is picked (equals 0), this messagebox will appear
                        else
                        {
                            cursor.SetLimit(10);
                            MessageBox.Show("Du må velge en verdi på høyre side. Standard verdi er 10. ");
                        }
                        progress = 30;
                        Console.Write("2");
                     /*   Thread t = new Thread(TimeTick);
                        t.Start();*/

                        Console.Write("Elapsed time1 is:" + sw.ElapsedMilliseconds );

                        if (cursor.Size() == 0)
                        {
                            Console.Write("3");
                            MessageBox.Show("Ditt søk returnerte ingen treff. Vennligst prøv et annet søkeord.");
                            Console.Write("Elapsed expired time is:" + sw.Elapsed);
                         //   t.Join();
                            break;
                        }
                        progress = 40;
                        Console.Write("4");
                        Console.Write("Elapsed time2 is:" + sw.Elapsed);
                        if (m_oWorker.CancellationPending == true)
                        {
                            e.Cancel = true;
                        }
                        App.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new ThreadStart(() =>
                       MainViewModel.TweetOC.Clear()));
                        App.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new ThreadStart(() =>
                        MainViewModel.GeoOC.Clear()));
                        progress = 50;
                        foreach (var item in cursor)
                            if (m_oWorker.CancellationPending == true)
                            {
                                e.Cancel = true;
                            }
                            else if (item.geo != null && item.text != null)
                            {

                                App.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new ThreadStart(() =>
                                 GeoOC.Add(item)));
                                TweetOC.Add(item);
                            }
                            else
                            {

                                App.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new ThreadStart(() =>
                                MainViewModel.TweetOC.Add(item)));
                            }
                        progress = 60;
                        var size = cursor.Size();
                        if (cursorLimit == 0)
                        {
                            cursorLimit = 10;
                        }
                        if (m_oWorker.CancellationPending == true)
                        {
                            e.Cancel = true;
                        }
                        if ( 
                            MessageBox.Show( "Du fikk" + " " + size + " " + "treff av" + " " + cursor.Count() + " " + "mulige. 'r'n" + " " +
                            "Ønsker du å hente ut de neste" + " " + cursorLimit + " " + "Svarene også?", "Antall mulig treff", MessageBoxButtons.YesNo) == DialogResult.Yes)
                        {   
                             var query2 = Query.And(Query.Matches("text", new BsonRegularExpression(new Regex(searchText, RegexOptions.IgnoreCase))));
                             var cursor2 = collection.Find(query2);
                            cursor2.Skip = cursorLimit;
                            cursor2.Limit = cursorLimit;
                            foreach (var item in cursor2)
                                if (m_oWorker.CancellationPending == true)
                                {
                                    e.Cancel = true;
                                }
                                else if (item.geo != null && item.text != null)
                                {

                                    App.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new ThreadStart(() =>
                                     GeoOC.Add(item)));
                                    TweetOC.Add(item);
                                }
                                else
                                {

                                    App.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new ThreadStart(() =>
                                    MainViewModel.TweetOC.Add(item)));
                                }
                        }

                        progress = 70;
                        System.Console.WriteLine("TweetViewCount:" + TweetOC.Count);
                        System.Console.WriteLine("GeoViewCount:" + GeoOC.Count);
                        Console.Write("Elapsed time3 is:" + sw.Elapsed);

                    //    t.Join();
                        progress = 100;
                        //return database;
                    }
                    catch (Exception)
                    {
                        throw new Exception("Something went wrong");
                    }
                }

                donewithwork = true;

            }
            else MessageBox.Show("Your search did not return a match. Please search for something else.");
            progress = 0;
        }
    }

执行搜索 wpf 时超时

使用多线程和AutoResetEvent应该很容易做到。代码应如下所示:

    // The AutoResetEvent is here to count time
    private AutoResetEvent event = new AutoResetEvent(false);
private YourMethod()
{
    Thread thread = new Thread(new ThreadStart(YourSearch));
    thread.Start();
    if (event.WaitOne(10000) == false)
    {
    // This should be reached only if the thread hasn't finished executing the search method after 10 seconds (10000 ms, you can change the parameter)
    // Show a message or whatever you want here, then abort thread:
    thread.Abort();
    }
}

您的搜索方法最后应该只有以下内容:

private void YourSearchMethod()
{
// Search whatever you want;
event.Set(); // Sets event (which triggers the WaitOne() call we used earlier)
}

我假设这是在 C# 中?看看这个

http://blogs.msdn.com/b/nikhil_agarwal/archive/2014/03/28/timeout-a-function-call-in-c.aspx