C#中的用户代码未处理ThreadStateException

时间:2015-10-22 06:52:09

标签: c# .net

我正在尝试编写一个能够从文件读入并收到ThreadStateException的C#表单。

这是我的Utility类,其中发生了错误。

public static class Utility {
    public static bool ExecuteWithTimeLimit(TimeSpan timeSpan, Action codeBlock) {
        try {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            Task task = Task.Factory.StartNew(() => codeBlock());
            task.Wait(timeSpan);
            sw.Stop();
            Handler.Log(String.Format("Total Runtime: {0} mins, {1} seconds.{2}{2}", sw.Elapsed.Minutes, sw.Elapsed.Seconds.ToString(), Environment.NewLine));
            return task.IsCompleted;
        } catch (AggregateException ae) {
            throw ae.InnerExceptions[0];
        }
    }

    public static List<String> ReadFile()
    {
        OpenFileDialog _FileDialog = new OpenFileDialog();
        _FileDialog.Filter = "CSV File (*.csv)|*.csv";

        //Error Occurring on the below line.
        if (_FileDialog.ShowDialog() == DialogResult.OK) {
            List<String> list = new List<String>();
            try
            {
                StreamReader reader = new StreamReader(_FileDialog.FileName);
                string line;
                while (!reader.EndOfStream)
                {
                    line = reader.ReadLine();
                    list.AddRange(line.Split(','));
                }
                reader.Close();
                return list;
            }
            catch (Exception ex) { return null; }
        }
        else
        {
            return null;
        }
    }
}

此行发生错误......

if (_FileDialog.ShowDialog() == DialogResult.OK) {

下面是调用函数的主要方法。

static class Program {
    //Limit to a 5 minute runtime.
    private static int TotalExecuteTime = 300000;

    [STAThread]
    static void Main() {
        Handler.CreateLog();
        bool CompletedExecution = Utility.ExecuteWithTimeLimit(TimeSpan.FromMilliseconds(TotalExecuteTime), () => {
            List<String> WordList = Utility.ReadFile();
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        });
        Handler.OpenLog();
    }

我哪里错了?

1 个答案:

答案 0 :(得分:1)

将此_FileDialog.ShowDialog()替换为STAShowDialog(_FileDialog)

添加这些辅助方法&amp;工作班:

 /* STAShowDialog takes a FileDialog and shows it on a background STA thread and returns the results.*/
    private DialogResult STAShowDialog(FileDialogdialog)
    {
            DialogState state = new DialogState();
            state.dialog = dialog;
            System.Threading.Thread t = new System.Threading.Thread(state.ThreadProcShowDialog);
            t.SetApartmentState(System.Threading.ApartmentState.STA);
            t.Start();
            t.Join();
            return state.result;
    }



/* Helper class to hold state and return value in order to call FileDialog.ShowDialog on a background thread.*/
   public class DialogState
  {
    public DialogResultresult;
    public FileDialogdialog;
    public voidThreadProcShowDialog()
    {
        result = dialog.ShowDialog();
    }
  }