IProgress synchronization

后端 未结 4 1762
夕颜
夕颜 2021-01-11 11:58

I have the following in C#

public static void Main()
{
    var result = Foo(new Progress(i =>
        Console.WriteLine(\"Progress: \" + i)));
         


        
4条回答
  •  无人及你
    2021-01-11 12:16

    The Progress<> class uses the SynchronizationContext.Current property to Post() the progress update. This was done to ensure that the ProgressChanged event fires on the UI thread of a program so it is safe to update the UI. Necessary to safely update, say, the ProgressBar.Value property.

    The problem with a console mode app is that it doesn't have a synchronization provider. Not like a Winforms or WPF app. The Synchronization.Current property has the default provider, its Post() method runs on a threadpool thread. Without any interlocking at all, which TP thread gets to report its update first is entirely unpredictable. There isn't any good way to interlock either.

    Just don't use the Progress class here, there is no point. You don't have a UI thread safety problem in a console mode app, the Console class is already thread-safe. Fix:

    static int Foo()
    {
        for (int i = 0; i < 10; i++)
            Console.WriteLine("Progress: {0}", i);
    
        return 1001;
    }
    

提交回复
热议问题