簡體   English   中英

SaveFileDialog不顯示在新線程中嗎?

[英]SaveFileDialog doesn't show in new thread?

很長一段時間以來,我一直對此問題感到困惑。 我使用System.Threading啟動新線程,如下所示:

ParameterizedThreadStart threadFileExport = FileExport;
Thread threadExport = new Thread(threadFileExport)
{
    IsBackground = true,
    Name = "threadExport",
    Priority = ThreadPriority.AboveNormal
};
threadExport.Start(_dataTable);

public void FileExport(object objTable)
{

     SaveFileDialog saveFileDialog = new SaveFileDialog
     {
         DefaultExt = "xlsx",
         Filter = "Excel 2007-2010|*.xlsx|" +
                  "Excel95,97,2003|*.xls|",
         FileName = "table.xlsx",
         Title = "Save as. . ."
     };
saveFileDialog.ShowDialog();
}

但是對話框不會顯示,並且似乎在執行“ ShowDialog”時線程將立即中止。 這是一個錯誤還是我犯了一個錯誤? 后台線程可以顯示保存文件對話框嗎?

不,必須像其他任何UI操作一樣,在UI線程上顯示一個對話框。

您創建的線程不會建立消息循環,因此您無法顯示它。

更好的方法是詢問用戶UI線程上的文件路徑,然后啟動導出線程,並向其傳遞文件名。 更好的是使用BackgroundWorker線程,以便您的UI保持響應。

更新:如果您不能使用BackgroundWorker,下面是我描述的替代代碼。 我假設您有一個類似於ExportDataTableToFile的方法,在獲取文件名后將調用該方法。

//
// Assuming your actual export method is similar to this:    
//
void ExportDataTableToFile(DataTable dataTable, string fileName) {
    // ...
}

我假設您在此處使用UI線程:

//
// You can ask for the file path first;
//
SaveFileDialog saveFileDialog = new SaveFileDialog
{
     DefaultExt = "xlsx",
     Filter = "Excel 2007-2010|*.xlsx|" +
              "Excel95,97,2003|*.xls|",
     FileName = "table.xlsx",
     Title = "Save as. . ."
};
saveFileDialog.ShowDialog();


string fileName = null;
if(saveFileDialog.Result == DialogResult.OK) // "else" case should be added
    fileName = saveFileDialog;

//
// And then start the thread:
//
Thread threadExport = new Thread(() => ExportDataTableToFile(_dataTable, fileName))
{
    IsBackground = true,
    Name = "threadExport",
    Priority = ThreadPriority.AboveNormal
};
threadExport.Start();

嘗試這個

在你班上

private object sync_temp = new object();

和線程方法

string path;
SaveFileDialog save = new SaveFileDialog();
// your code to do with "save"
Action ac = () => { lock (sync_temp) { save.ShowDialog(); } };
Invoke(ac);
lock (sync_temp)
{
   path = save.FileName;
}

或將該線程標記為STAThread

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM