簡體   English   中英

在另一個線程運行時延遲主線程

[英]Delay main thread while another thread is running

我想在自己的線程中導入CSV文件。 在導入和處理文件時,我想延遲/停止主線程,直到處理結束。 請參見下面的代碼:

// 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創建的。您可以如下所示使用task或async關鍵字。

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版本。

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;
}

暫無
暫無

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

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