2010-11-23 25 views
1

假設我有一個HttpHelper類具有GetResponseStream(),即上傳請求數據顯示,通過事件StatusChanged & ProgressChanged進展。需要關於如何做嚮導功能異步/非阻塞

public MemoryStream GetResponseStream() { 
    ... 
    Status = Statuses.Uploading; // this doesn't raise StatusChanged 
    // write to request stream 
    ... // as I write to stream, ProgressChanged doesn't get raised too 
    Status = Statuses.Downloading; // this too 
    // write to response stream 
    ... // same here 
    Status = Statuses.Idle; // this runs ok. Event triggered, UI updated 
} 

代碼@pastebinGetRequestStream()上線76類本身工作正常,除了使用類需要調用它像下面

HttpHelper helper = new HttpHelper("http://localhost/uploadTest.php"); 
helper.AddFileHeader("test.txt", "test.txt", "text/plain", File.ReadAllBytes("./test.txt")); 
helper.StatusChanged += (s, evt) => 
{ 
    _dispatcher.Invoke(new Action(() => txtStatus.Text = helper.Status.ToString())); 

    if (helper.Status == HttpHelper.Statuses.Idle || helper.Status == HttpHelper.Statuses.Error) 
     _dispatcher.Invoke(new Action(() => progBar.IsIndeterminate = false)); 

    if (helper.Status == HttpHelper.Statuses.Error) 
     _dispatcher.Invoke(new Action(() => txtStatus.Text = helper.Error.Message)); 
}; 
helper.ProgressChanged += (s, evt) => 
{ 
    if (helper.Progress.HasValue) 
     _dispatcher.Invoke(new Action(() => progBar.Value = (double)helper.Progress)); 
    else 
     _dispatcher.Invoke(new Action(() => progBar.IsIndeterminate = true)); 
}; 
Task.Factory.StartNew(() => helper.GetResponseString()); 

如果我呼籲使用

helper.GetResponseString(); 

那麼該類本身將工作類,但事件似乎沒有被提出。我認爲這與UI線程被阻止有關。我該如何重新編碼班級,使其更容易/更清潔,以供使用班級使用,並且不需要所有的東西。

此外,我想知道什麼導致事件/用戶界面不更新。即使代碼是同步的,它不能運行屬性改變/事件反正它在讀/寫之後呢?

+0

您應該將PasteBin語法突出顯示設置爲C#。 http://pastebin.com/FeAPB6rU – SLaks 2010-11-23 02:25:24

+0

@SLaks,謝謝你通知我,一定是一直在做PHP的PHP忘了,忘了改變語言 – 2010-11-23 03:01:35

回答