Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 需要关于如何使函数异步/非阻塞的指导吗_C#_Multithreading_Asynchronous_Task_Dispatcher - Fatal编程技术网

C# 需要关于如何使函数异步/非阻塞的指导吗

C# 需要关于如何使函数异步/非阻塞的指导吗,c#,multithreading,asynchronous,task,dispatcher,C#,Multithreading,Asynchronous,Task,Dispatcher,假设我有一个HttpHelper类,它有一个GetResponseStream(),该类通过事件StatusChanged&ProgressChanged上传显示进度的请求数据 public MemoryStream GetResponseStream() { ... Status = Statuses.Uploading; // this doesn't raise StatusChanged // write to request stream ... //

假设我有一个
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
}
代码<代码>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线程被阻塞有关。如何重新编码该类,使使用它的类更容易/更干净地使用它,而不需要所有的
\u分派器
&
任务
内容


另外,我想确定是什么导致事件/用户界面不更新。即使代码是同步的,它也不能在读/写之后运行属性changed/events吗

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

应将PasteBin语法突出显示设置为C@SLaks,谢谢你通知我这件事,一定是做了PHP yest,忘了更改语言虽然这可能是一个很好的建议,但我想补充一点,因为在某些情况下,这可能不太好:这个建议的一个问题是,只要工作还在进行,它就会消耗一个线程。这在客户端代码中不太可能是个问题(这似乎就是问题所在),但在服务器端代码中,它将无法实现异步操作。完全异步使用网络类可以更节省地使用线程,这有时有助于提高服务器的可伸缩性。(但在这里可能会过度工程化。)