在另一个线程 运行 时延迟主线程

Delay main thread while another thread is running

我想在自己的线程中导入 CSV 文件。在导入和处理文件时,我想 delay/stop 主线程,直到处理结束。请看下面的代码:

// Read from CSV file in a seperate thread
new Thread(() =>
{
    Thread.CurrentThread.IsBackground = true;

    reader = new CSVReader(myFile);
    reader.DataReader();


    // Get temperature and time data from CSV file
    // and copy the data into each List<String>
    Temperature = new List<string>(reader.GetTemperature());
    Time = new List<string>(reader.GetTime());

}).Start();

// Bind data to GridView
dtgCsvData.ItemsSource = Time.Zip(Temperature, (t, c) => new { Time = t, Temperature = c });

当应用程序是运行时发生错误,因为两个列表都是空的。

如何实现?

您可能真的不想停止主线程。如果这是一个 GUI 应用程序,您仍然希望主 UI 线程响应 Windows 消息等。你想要的是 运行 读取数据后的那段代码。为什么不让工作线程在读取数据后调用它?

这是使用 linqpad 创建的...您可以使用任务或异步关键字,如下所示。

void Main()
{   
    Task<TimeAndTemp> timeAndTempTask = GetTimeAndTemp();
    timeAndTempTask.ContinueWith (_ => 
        {
            timeAndTempTask.Result.Time.Dump();
            timeAndTempTask.Result.Temperature.Dump();
        }); 
}

Task<TimeAndTemp> GetTimeAndTemp()
{
    var tcs = new TaskCompletionSource<TimeAndTemp>();

    new Timer (_ => tcs.SetResult (new TimeAndTemp())).Change (3000, -1);

    return tcs.Task;
}

public class TimeAndTemp
{
    public DateTime Time = DateTime.Now;
    public int Temperature = 32;
}

使用 async await 关键字的异步版本。

async void Main()
{   
    TimeAndTemp tt = await GetTimeAndTemp();

    tt.Time.Dump();
    tt.Temperature.Dump();
}

async Task<TimeAndTemp> GetTimeAndTemp()
{
    return new TimeAndTemp();
}

public class TimeAndTemp
{
    public DateTime Time = DateTime.Now;
    public int Temperature = 32;
}