为什么在将它用作ThreadStart()参数时需要重载该方法?

时间:2017-10-10 23:49:38

标签: c#

我想使用单独的线程保存文件。没有使用线程的经验。

private ObservableCollection<PersonEntitiy> allStaff;
private Thread dataFileTransactionsThread;

#region Constructor
public staffRepository() {
    allStaff = getStaffDataFromTextFile();
    dataFileTransactionsThread = new Thread(new ThreadStart(UpdateDataFile));
}
#endregion

public void UpdateDataFile(ObservableCollection<PersonEntitiy> allStaff) {

    dataFileTransactionsThread.Start();
    System.Diagnostics.Debug.WriteLine("dataFileTransactions Thread Status:"+ dataFileTransactionsThread.ThreadState);

    string containsWillBeSaved = "";

    // ...

    File.WriteAllText(fullPathToDataFile, containsWillBeSaved);
    System.Diagnostics.Debug.WriteLine("Data Save Successfull");

    // depricated but did not deside what is better to use instead yet
    dataFileTransactionsThread.Suspend(); 
    System.Diagnostics.Debug.WriteLine("dataFileTransactions Thread Status:" + dataFileTransactionsThread.ThreadState);

}

IDE显示UpdateDataFile()尚未超载。如果要添加以下代码,将编译应用程序,但我需要了解UpdateDataFile() - 没有参数的方法重载的作用。

// Overload is required but I don't understand why
public void UpdateDataFile() {

}

1 个答案:

答案 0 :(得分:2)

您需要重载它,因为ThreadStart的构造函数采用无参数void函数,并且您尝试使用带参数的函数。您似乎也从它的方法中启动了线程,这不应该发生。我建议您尝试以下方法:

private ObservableCollection<PersonEntitiy> allStaff;
private Thread dataFileTransactionsThread;

#region Constructor
public staffRepository() {
    allStaff = getStaffDataFromTextFile();
    dataFileTransactionsThread = new Thread(UpdateDataFileThread);
}
#endregion

public void UpdateDataFile(ObservableCollection<PersonEntitiy> allStaff)     
{
    dataFileTransactionsThread.Start(allStaff);

    // If you want to wait until the save finishes, uncomment the following line
    // dataFileTransactionsThread.Join();
}

private void UpdateDataFileThread(object data) {
    var allStaff = (ObservableCollection<PersonEntitiy>)data;

    System.Diagnostics.Debug.WriteLine("dataFileTransactions Thread Status:"+ dataFileTransactionsThread.ThreadState);

    string containsWillBeSaved = "";

    // ...

    File.WriteAllText(fullPathToDataFile, containsWillBeSaved);

    System.Diagnostics.Debug.WriteLine("Data Save Successfull");

    System.Diagnostics.Debug.WriteLine("dataFileTransactions Thread Status:" + dataFileTransactionsThread.ThreadState);

}

请注意,在您必须重新构建UpdateDataFile对象之前,您只能致电dataFileTransactionsThread一次,如果您想避免这种情况,并且一心想要使用您可以构建的对象公共UpdateDataFile

中的线程对象