假设我的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
}
代码 @pastebin 。第76行GetRequestStream()
。类本身工作正常,除了using类需要像下面那样调用它
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无法更新。即使代码是同步的,也不能运行属性更改/事件反正,它的读/写后是什么?