2010-11-23 27 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

回答