感謝您閱讀本主題。C#(WPF)異步線程與界面到GUI
對於一個新的WPF應用程序(用C#構建)我有一個關於設計的問題。 過去幾天我已經閱讀了很多關於C#中的異步編程(基於.NET 4.5)。
我們想要做的是:創建一個新的異步線程,它執行獨立的後臺任務。當這個線程有可用數據時:然後將這些數據發送到主程序(通過公共接口)。所以,線程將在主程序中設置數據並立即再次返回到線程。數據更改後,主程序將引發一個事件(INotifyPropertyChanged)。
什麼是創建這個異步線程的最佳方式?或者至少,設計此功能的最佳方式是什麼?
目前我已經構建了一個創建線程的應用程序。 這不目前工作異步:
public MainWindow()
{
InitializeComponent();
InitGuiInterface(this);
//Create thread
new OuterLabel_Thread(this);
}
和類 「OuterLabel_Thread.cs」 這裏下面:提前
public class OuterLabel_Thread
{
private MainWindow context = null;
private bool exit = false;
private int count = 0;
public OuterLabel_Thread(MainWindow context)
{
this.context = context;
Console.WriteLine("Running sample thread");
Thread thread = new Thread(delegate()
{
Console.WriteLine("Sample thread started");
//start new task
//run();
Task.Factory.StartNew(run);
});
thread.Start();
}
public void Exit()
{
exit = true;
}
private void run()
{
while (!exit)
{
DateTime Time1 = DateTime.Now;
if (context != null && context.GuiInterface != null)
{
//context.GuiInterface.UpdateThreadCount(count, "label_code_content");
}
Console.WriteLine("Background thread count = " + count);
count++;
if (count > 1000)
{
exit = true;
}
//Console.WriteLine((DateTime.Now - Time1).TotalMilliseconds.ToString());
Thread.Sleep(10);
}
}
}
非常感謝! 親切的問候,
Rein。
爲什麼不只是使用異步等待?這將使管理UI線程和避免交叉線程錯誤變得容易。你可以避免重複性問題,而不是試圖管理你自己的線程。 – CodeMonkey
我沒有太多的使用異步和等待的經驗。我知道這些說明是幹什麼的。 您的建議仍然基於線程的使用情況嗎?在這種情況下,我該如何調用線程? – Rein92
您是否正在尋找一種可以連續提供數據的服務,或者只需點擊一個按鈕即可開始一項長時間運行的任務? – CodeMonkey