假设我有一个HttpHelper类,它有一个GetResponseStream(),它通过events 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
}代码@pastebin。GetRequestStream()在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线程被阻塞有关。如何对类进行重新编码,使使用类更容易/更干净,而不需要使用所有的_dispatcher & Task。
另外,我想确切地知道导致事件/UI不更新的原因。即使代码是同步的,它也不能运行属性更改/事件,毕竟是在读/写之后吗?
发布于 2010-11-23 03:54:06
您应该考虑使用BackgroundWorker,而不是自己手工制作。使用ReportProgress将处理状态传递给UI线程。
https://stackoverflow.com/questions/4252156
复制相似问题