需要指导如何使功能异步/非阻塞

时间:2010-11-23 02:20:51

标签: c# multithreading asynchronous task dispatcher

假设我的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无法更新。即使代码是同步的,也不能运行属性更改/事件反正,它的读/写后是什么?

1 个答案:

答案 0 :(得分:2)

你应该考虑使用BackgroundWorker而不是亲自手工制作。使用ReportProgress将处理状态传递给UI线程。