【发布时间】:2016-05-31 05:36:53
【问题描述】:
我没有维护线程或会话,但是定义的变量在回发期间丢失,因为创建了一个新线程。想法?
每次单击 button1 或 button2 时,currentthreadid 和 sessionid 都会发生变化。我更关心正在创建的新线程。请帮忙!
这是我的 WebForm1.aspx 代码
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="UpdatePanelTest2.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" EnablePartialRendering="true" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Before Click" />
<asp:Button ID="Button1" runat="server" Text="Button1" OnClick="Button1_Click" CausesValidation="false"/>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<asp:Button ID="Button2" runat="server" Text="Button2" OnClick="Button2_Click"/>
</form>
</body>
</html>
这是我的 WebForm1.aspx.cs 代码
namespace UpdatePanelTest2
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string currentthreadid = AppDomain.GetCurrentThreadId().ToString();
string sessionid = Session.SessionID;
if (IsPostBack) { }
if (IsAsync) { }
if (IsPostBackEventControlRegistered) { }
if (ScriptManager1.IsInAsyncPostBack) { }
}
protected void Page_Init(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
this.Label1.Text = "After Click";
}
protected void Button2_Click(object sender, EventArgs e)
{
}
}
}
我的 web.config 文件
<?xml version="1.0"?>
<!-- For more information on how to configure your ASP.NET application, please visit http://go.microsoft.com/fwlink/?LinkId=169433 -->
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
</configuration>
更新
我需要它作为回发调用的同一个线程的原因是我维护了某些变量,然后将这些变量重新用于当前池线程
代码:
private static readonly ThreadLocal<PageContext> _context = new ThreadLocal<PageContext>(typeof(PageContext), "_context", true);
private string[] _path;
public static PageContext ForCurrentThread
{
get { return _context.Value ?? (_context.Value = new PageContext()); }
}
public void Initialize(HttpRequest _request)
{
somestring = null;
}
public string somestring { get; set; }
当页面第一次加载时, somestring 被赋予一个值,然后其他类使用相同的上下文并重新使用该 somestring 值。如果为回发请求创建了新线程,这将不起作用。
【问题讨论】:
-
无法理解您的问题。您只想存储一次价值?
-
有一个类似的线程 - 请点击下面的链接。 stackoverflow.com/questions/222999/…
-
你想让哪个变量保持不变?
-
根据'更新'让我们说'somestring'
标签: c# asp.net multithreading session-state pageload