在线程中返回/设置值

时间:2015-11-09 15:36:29

标签: c# asp.net multithreading

我试图在C#中打开一个OpenFileDialog(代码隐藏,在asp.net页面上)。因为常规引用和system.windows.form有一些冲突,我必须在一个线程中使用OpenFileDialog框,如下所示:

protected void Button1_Click(object sender, EventArgs e)
{
    Thread newThread = new Thread(new ThreadStart(BrowseForFile));
    newThread.SetApartmentState(ApartmentState.STA);
    newThread.Start();     
}

static void BrowseForFile()
{
    System.Windows.Forms.OpenFileDialog MyFile = new System.Windows.Forms.OpenFileDialog();
    if (MyFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
    {

    }
}

页面的工作方式意味着它必须在C#中 - 使用asp.net的文件上传不会起作用。

现在,OpenFileDialog显示正常,我可以从中获取值,但理想情况下我需要将值传递到线程(BrowseForFile)并让它与页面上的其他控件一起使用,以便进行设置。但是,我使用线程非常新。

有人可以告诉我,基本上,如何从Button1_Click到BrowseForFile获取一个整数,以及如何在BrowseForFile页面上设置标签?

1 个答案:

答案 0 :(得分:0)

如果你使用现代版的.net,你可以使用async-await。这使您可以更轻松地与对话框进行通信并将数据传递给执行后台工作的线程。

能够使用async-await:

  • 声明您的函数async
  • 让您的函数返回Task而不是void和Task <TResult&gt;而不是TResult。
    • 有一个例外:事件处理程序可能返回void
    • 在异步功能中使用Task.Run启动其他线程
    • 当另一个线程正在运行时,你可以做其他事情
    • 如果您需要结果:call await Task。

在您的情况下,您必须将您的线程类更改为包含线程类中的代码的过程。此程序可以在任何类别中。它必须声明为异步并返回Task而不是void:

当然,您必须将您的线程类更改为异步过程:

private async Task MyThreadProcedureAsync(string fileName)
{
    // do something really slow with fileName and return void
}



protected async void Button1_Click(object sender, EventArgs e)
{
    string fileName = this.BrowseForFile();
    if (!String.IsNullOrEmpty(fileName))
    {
        var myTask = Task.Run( () => MyThreadProcedureAsync(fileName))
        // if desired do other things.
        // before returning make sure the task is ready:
        await myTask;
        // during this wait the UI keeps responsive
    }
}

private string BrowseForFileName()
{
    using (var dlg = new System.Windows.Forms.OpenFileDialog())
    {
        // if needed set some properties; show the dialog:
        var dlgResult = dlg.ShowDialog(this);
        if (dlgResult == System.Windows.Forms.DialogResult.OK)
        {
            return dlg.FileName;
        }
        else
        {
            return null;
        }
    }
}
相关问题