C# 重定向前的时间延迟

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10141504/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 12:37:20  来源:igfitidea点击:

Time delay before redirect

c#timedelay

提问by user1331344

I create a register page for my web application. The application require that after user successfully register a new account, the page will show a message "Register successfully", then wait for 5 seconds before switch to Login page. I used Thread.Sleep(5000). It wait for 5 seconds but it does not display the message. Can anyone help me?

我为我的 Web 应用程序创建了一个注册页面。应用程序要求用户成功注册新帐户后,页面将显示“注册成功”信息,然后等待 5 秒后切换到登录页面。我用过Thread.Sleep(5000)。它等待 5 秒钟,但不显示消息。谁能帮我?

void AccountServiceRegisterCompleted(object sender, RegisterCompletedEventArgs e)
    {
        if (e.Result)
        {
            lblMessage.Text = "Register successfully";

            Thread.Sleep(5000); 
            this.SwitchPage(new Login());
        }
        else
        {
            ...
        }
    }

采纳答案by lorond

Thread.Sleep(5000)only suspends your thread for 5 seconds - no code onto this thread will be executed during this time. So no messages or anything else.

Thread.Sleep(5000)仅挂起您的线程 5 秒钟 - 在此期间不会执行此线程上的任何代码。所以没有消息或其他任何东西。

If it's an ASP.NET app, client doesn't know what's going on on server and waits server's response for 5 seconds. You have to implement this logic manually. For example, either using JavaScript:

如果它是一个 ASP.NET 应用程序,客户端不知道服务器上发生了什么并等待服务器的响应 5 秒。您必须手动实现此逻辑。例如,要么使用 JavaScript:

setTimeout(function(){location.href = 'test.aspx';}, 5000);

or by adding HTTP header:

或通过添加 HTTP 标头:

Response.AddHeader("REFRESH","5;URL=test.aspx");

or metatag:

meta标记:

<meta http-equiv="refresh" content="5; url=test.aspx" />

see more info.

查看更多信息

If it's a desktop application you could use something like timers. And never make main thread (UI Thread) hangs with something like Thread.Sleep.

如果它是桌面应用程序,您可以使用timers 之类的东西。并且永远不要让主线程(UI 线程)挂起像 Thread.Sleep 这样的东西。

回答by Sunil Acharya

Only meta tag is enough to redirect to another page

只有元标记就足以重定向到另一个页面

ad meta tag dynamically

动态广告元标记

Response.AddHeader("REFRESH", "5;URL=~/account/login");

Response.AddHeader("REFRESH", "5;URL=~/account/login");

This code will ad a meta tag to current page and your page will redirect to another page in specified time like above.

此代码将向当前页面添加元标记,您的页面将在指定时间重定向到另一个页面,如上所示。