首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >需要指导如何使功能异步/非阻塞

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

Stack Overflow用户
提问于 2010-11-23 02:20:51
回答 1查看 380关注 0票数 1

假设我有一个HttpHelper类,它有一个GetResponseStream(),它通过events StatusChanged & ProgressChanged上传显示进度的请求数据。

代码语言:javascript
复制
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线。类本身工作正常,除非使用类需要像下面这样调用它

代码语言:javascript
复制
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());

如果我打电话给全班

代码语言:javascript
复制
helper.GetResponseString();

这样,类本身就能工作,但事件似乎不会被引发。我认为这与UI线程被阻塞有关。如何对类进行重新编码,使使用类更容易/更干净,而不需要使用所有的_dispatcher & Task

另外,我想确切地知道导致事件/UI不更新的原因。即使代码是同步的,它也不能运行属性更改/事件,毕竟是在读/写之后吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2010-11-23 03:54:06

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4252156

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档