问题描述
我是C#线程方面的新手.我正在设法弄清如何发出100K Web请求,具有一定程度的并行性,并向GUI实时报告进度:
I am a neophyte at C# threading. I am trying to get my head around how to make 100K web requests, with some degree of parallelism, and report progress real-time to the GUI:
urls processed so far: ######
total moved so far: ######
timed out so far: ####3
我正在阅读Albarhari兄弟在 C#5.0中的 C#5.0 596>中的596ff页,有关进度报告.在这一点上,我看不到如何在Progress实例中以线程安全的方式增加这些计数器的数量,以及UI的更新方式/确切位置.在示例中,EVen专门讨论了写入控制台和写入GUI之间的区别,本书使用Console.WriteLine
.我将不胜感激一个示例,该示例准确显示了Progress实例中发生的情况-例如,增加一些int变量并写入文本框.
I am reading pages 596ff in C# 5.0 in a Nutshell by the Albahari brothers, the section on Progress Reporting. At this point, I don't see how in the Progress instance these counters would be incremented in a thread-safe manner, and exactly how/where the UI gets updated. EVen in the example specifically discussing the differences between writing to the console and writing to the GUI, the book uses Console.WriteLine
. I'd be grateful for an example showing exactly what occurs in the Progress instance -- incrementing some int variables and writing to a textbox, for example.
推荐答案
我有一个我的博客上的演练,特别指出了警告:
I have a walkthrough on my blog, in particular pointing out the caveats:
-
IProgress<T>.Report
是异步的,因此,如果您发送的对象是不可变的,则效果最佳. - 按照惯例,传递给您的TAP方法的
IProgress<T> progress
可能是null
,因此请在报告进度之前进行检查. -
Progress<T>
最适合与UI或其他单线程SynchronizationContext
一起使用. - 从
Progress<T>
的处理程序引发的异常直接进入SynchronizationContext
,因此避免引发进度报告处理程序的异常.
IProgress<T>.Report
is asynchronous, so it works best if the object you send it is immutable.- By convention, the
IProgress<T> progress
passed into your TAP method may benull
, so check for that before reporting progress. Progress<T>
works best with a UI or other single-threadedSynchronizationContext
.- Exceptions raised from
Progress<T>
's handler go directly to theSynchronizationContext
, so avoid throwing exceptions from the progress report handler.
这篇关于使用阿尔巴哈里(Albarhari)描述的IProgress接口所需的特定工作示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!