线程化c# ASP.NET时丢失变量

本文关键字:变量 NET ASP 线程 | 更新日期: 2023-09-27 17:54:58

我正在尝试将xml文件反序列化为列表,并且我希望用户能够选择要反序列化的文件。

static List<string> mylist = new List<string>();
string filename;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
    Thread newThread = new Thread(new ThreadStart(ThreadMethod));
    newThread.SetApartmentState(ApartmentState.STA);
    newThread.Start();
}
public void ThreadMethod()
{
    OpenFileDialog dlg = new OpenFileDialog();
    dlg.ShowDialog();
    filename = dlg.FileName;
}
protected void ButtonDeserialize_Click(object sender, EventArgs e)
{

    var serializer = new XmlSerializer(typeof(List<string>));
    using (var stream = File.OpenRead(filename))
    {
        var other = (List<string>)(serializer.Deserialize(stream));
        mylist.Clear();
        mylist.AddRange(other);
    }
}

线程结束后,文件名变为空。知道为什么会这样吗?顺便说一下,我必须使openfiledialog像这样,因为这是唯一的方法,为我工作。提前感谢!

线程化c# ASP.NET时丢失变量

替换此语句:

dlg.ShowDialog();
filename = dlg.FileName;
与这个:

DialogResult result = dlg.ShowDialog();
if(result == DialogResult.OK)   
  filename = dlg.FileName;

使用FileUploadControl解决了这个问题。在Web应用程序上更容易和工作完美。

protected void ButtonDeserialize_Click(object sender, EventArgs e)
{
    if (FileUploadControl.HasFile)
    {
        try
        {
            filename = Path.GetFileName(FileUploadControl.FileName);
            pathname = Path.GetDirectoryName(filename);
        }
        catch (Exception ex)
        {
            LabelMessage.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
        }
    }