Windows窗体应用程序中出现“当前线程必须在单线程单元中”错误

问题描述 投票:-1回答:1

我正在尝试构建一个包含进度条的简单Windows窗体应用程序。今天打开项目时,我收到一条消息,提示Visual Studio无法正确关闭,需要还原Form1.cs文件。该代码之前工作正常,但现在我收到此错误消息:

An exception of type 'System.Threading.ThreadStateException' occurred in System.Windows.Forms.dll but was not handled in user code

Additional information: Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it. This exception is only raised if a debugger is attached to the process.

自上次成功运行以来,我尚未对Form1.cs文件进行任何更改。这是Form1.cs的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PhotoPackager
{
    public partial class Form1 : Form
    {
        string inputFolderPath;
        string outputFolderPath;
        Logger logger = new Logger();
        public Form1()
        {
            InitializeComponent();
            Shown += new EventHandler(Form1_Shown);

            // To report progress from the background worker we need to set this property
            backgroundWorker1.WorkerReportsProgress = true;
            // This event will be raised on the worker thread when the worker starts
            backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
            // This event will be raised when we call ReportProgress
            backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
        }
        void Form1_Shown(object sender, EventArgs e)
        {
            // Start the background worker
            backgroundWorker1.RunWorkerAsync();
        }
        // On worker thread so do our thing!
        void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            using (var fbd = new FolderBrowserDialog())
            {
                DialogResult result = fbd.ShowDialog();

                if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
                {
                    processFolder(fbd.SelectedPath);
                }
            }
        }
        // Back on the 'UI' thread so we can update the progress bar
        void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            // The progress percentage is a property of e
            progressBar1.Value = e.ProgressPercentage;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // Start the background worker
            backgroundWorker1.RunWorkerAsync();

        }

        private void processFolder(string selectedPath)
        {
            inputFolderPath = selectedPath;
            FolderProcessor folderProcessor = new FolderProcessor(logger);
            folderProcessor.processFolder(inputFolderPath, outputFolderPath, backgroundWorker1.ReportProgress);
        }
    }
}

backgroundWorker1_DoWork中的以下行上引发了错误:

DialogResult result = fbd.ShowDialog();
c# multithreading winforms backgroundworker
1个回答
1
投票

检查Program.cs。看来您缺少[STAThread]属性->

namespace AnotherExample
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.