2013-10-10 28 views
-3

我是新來的winform,我無法弄清楚如何使用BackgroundWorker。如何在Winform c中使用B​​ackgroundWorker#

基本上就是我想要做的是這樣的:

我有1個表格2個按鈕:「導入」和「退出」。當調用ImporButton_Click時,它所做的就是創建一個HttpListener並監聽給定的URL。 ExitButton_Click關閉表單。

問題是當我按下「導入」表單卡住,它處於「無響應」狀態,直到有人調用監聽器並釋放它。

我正在嘗試根據BackgroundWorker如何幫助我克服「卡住」問題。我不知道如何調用backgroundWorker1_DoWork方法

這裏是我到目前爲止的代碼:

//Program.cs 
static class Program 
{ 
    /// <summary> 
    /// The main entry point for the application. 
    /// </summary> 
    [STAThread] 
    static void Main() 
    { 
     Application.EnableVisualStyles(); 
     Application.SetCompatibleTextRenderingDefault(false); 
     Application.Run(new ConfigurationForm()); 
    } 
} 

//ConfigurationForm.cs 
public partial class ConfigurationForm : Form 
{ 
    public ConfigurationForm() 
    { 
     InitializeComponent(); 
     UrlTextBox.Text = @"enter URL here"; 
    } 

    private void ImporButton_Click(object sender, EventArgs e) 
    { 
     try 
     { 
      String urlToListen = UrlTextBox.Text; 

      //Invoke MyListener 
      MyListener.StartListen(urlToListen); //assume this is implemented 
     } 
     catch (Exception exception) 
     { 
      string errorMsg = String.Format("An exception occured = {0}", exception); 
      MessageBox.Show(errorMsg); 
     } 
    } 

    private void ExitButton_Click(object sender, EventArgs e) 
    { 
     this.Close(); 
    } 


    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) 
    { 
    } 
} 

所以,現在怎麼辦?我如何調用backgroundWorker1_DoWork?

10倍的人誰可以幫助

+0

你不顯示代碼,你真正的問題在於離開*「假設這是實現「* :)例如,請參閱[this](http://stackoverflow.com/questions/10017564/url-mapping-with-c-sharp-httplistener)或[this](http://stackoverflow.com/問題/ 13385633/serving-large-files-with-c-sharp-httplistener) –

+0

好吧,這正是我的觀點。我不知道從哪裏調用backgroundWorker1。 – Dardar

+0

你需要一個教程;網上已經有很多,請嘗試[MSDN](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker%28v=vs.95%29.aspx)。 –

回答

1

你需要調用這個方法RunWorkerAsync

backgroundWorker1.RunWorkerAsync(); 

如果你想通過DoWorkEventArgs傳遞一些argument進入處理程序DoWork,嘗試RunWorkerAsync第二個重載:

backgroundWorker1.RunWorkerAsync(yourArgument); 
+0

但我從哪裏打電話?從ImporButton_Click()方法?我的MyListener.StartListen(urlToListen)邏輯應該在RunWorkerAsync()內嗎? – Dardar

+0

@達爾它取決於你想要你的'BackgroundWorker'做什麼。在調用方法之後,你的'BackgroundWorker'將在'DoWork'事件處理器中完成你想要的事情。 –

相關問題