2009-05-20 83 views
1

編輯C#winforms:我的GUI和邏輯分離是否正確完成?

基於下面的建議發送邏輯代碼GUI的代表,我想出了這樣的代碼:

Action ClearFunction = new Action(()=>Invoke(new Action(delegate() { ResultsBox.Clear(); }))); 

是否有可能縮短呢?


這是我的C#窗體表單程序的一部分。

當我開始轉換爲使用另一個線程的代碼,它開始覺得很這些混沌,我產生的線程和創建包裹在代表這樣的邏輯代碼可以實際使用的GUI公共方法。

請提供更好的成語或改進架構的建議。謝謝。

// form1.cs 
    public void ClearResultsBox() 
    { 
     ResultsBox.Clear(); 
    } 

    public void PrintResults(string s) 
    { 
     ResultsBox.AppendText(s); 
    } 

    private void SearchButton_Click(object sender, EventArgs e) 
    { 
     var t = new Thread(() => SearchCore.Execute(DirectoryBox.Text, SearchBox.Text, this)); 
     t.Start(); 
    } 

    // logic.cs 
class SearchCore 
{ 
    delegate void ClearFunction(); 
    delegate void AppendFunction(string a); 

    static ClearFunction clear; 
    static AppendFunction print; 

    public static void Execute(string path, string searchterm, MainForm form) 
    { 
     clear = new ClearFunction(() => form.Invoke(new ClearFunction(form.ClearResultsBox))); 
     print = new AppendFunction(s => form.Invoke(new AppendFunction(form.PrintResults), s)); 

     clear(); 
+0

@senfo沒有真正更給它。執行是一種長時間運行的方法(2分鐘),每隔幾秒鐘輸出一次。 – Unknown 2009-05-20 01:20:40

+0

您能否提供一些您想要完成的更多細節?你有一些非常重大的設計缺陷,但我不想讓你錯誤的方向,直到我明白你想去的地方。例如,你是否只是試圖保持UI的響應? – senfo 2009-05-20 01:22:04

回答

3

我在表單和searchCore之間沒有循環引用。 你爲什麼不使搜索邏輯頂嘴,形成通過回調?這樣搜索並不需要知道表單並且更容易測試。