C# 不等待时异步等待

C# 不等待时异步等待,c#,.net,winforms,async-await,C#,.net,Winforms,Async Await,我正在VS2013、.NET FW 4.5.1中开发WinForms应用程序。以下是我的简化代码,其中包含有关结构的内联注释: // Progress object implementing IProgress<MyProgressData> var progressCallback = new Progress<MyProgressData>(); // listOfMyList is actually List<List<MyObject>>

我正在VS2013、.NET FW 4.5.1中开发WinForms应用程序。以下是我的简化代码,其中包含有关结构的内联注释:

// Progress object implementing IProgress<MyProgressData>
var progressCallback = new Progress<MyProgressData>();

// listOfMyList is actually List<List<MyObject>>, which contains list of
// list of MyObject's which will be executed as tasks at once.
// For example, this would be sample structure for list of lists:
// List1
//   MyObject1
//   MyObject2
//   MyObject3
// List2
//   MyObject4
//   MyObject5
//   MyObject6
// List1's and List2's objects would be executed as all tasks at once, but List1 and List2 respectively
// would be executed one after another (because of resources usage inside TASK CODE)
foreach (var myItem in listOfMyList)
{
  var myList = myItem.ToList();

  // Create a list of tasks to be executed (20 by default; each taking from 30-60 seconds)
  // Here cs is actually MyObject
  var myTasks = myList.Select(cs => Task.Run(async () =>
  {
    // TASK CODE (using cs as an input object and using "cancellationToken.ThrowIfCancellationRequested();" inside execution to cancel executing if requested)
  }, cancellationToken));

  await Task.WhenAll(myTasks); // Wait for all tasks to finish

  // Report progress to main form (this actually calls an event on my form)
  await Task.Run(() => progressCallback.Report(new MyProgressData() { props }), CancellationToken.None);
}

MyProblematicMethod中的每个方法都使用wait来等待异步方法,并且不会被多次调用。

根据Glorin的建议,IProgress.Report在触发事件处理程序后立即返回,我创建了Progress类的精确副本,它使用synchronizationContext。Send而不是Post:

public sealed class ProgressEx<T> : IProgress<T>
{
    private readonly SynchronizationContext _synchronizationContext;
    private readonly Action<T> _handler;
    private readonly SendOrPostCallback _invokeHandlers;

    public event EventHandler<T> ProgressChanged;

    public ProgressEx(SynchronizationContext syncContext)
    {
        // From Progress.cs
        //_synchronizationContext = SynchronizationContext.CurrentNoFlow ?? ProgressStatics.DefaultContext;
        _synchronizationContext = syncContext;
        _invokeHandlers = new SendOrPostCallback(InvokeHandlers);
    }

    public ProgressEx(SynchronizationContext syncContext, Action<T> handler)
        : this(syncContext)
    {
        if (handler == null)
            throw new ArgumentNullException("handler");
        _handler = handler;
    }

    private void OnReport(T value)
    {
        // ISSUE: reference to a compiler-generated field
        if (_handler == null && ProgressChanged == null)
            return;
        _synchronizationContext.Send(_invokeHandlers, (object)value);
    }

    void IProgress<T>.Report(T value)
    {
        OnReport(value);
    }

    private void InvokeHandlers(object state)
    {
        T e = (T)state;
        Action<T> action = _handler;
        // ISSUE: reference to a compiler-generated field
        EventHandler<T> eventHandler = ProgressChanged;
        if (action != null)
            action(e);
        if (eventHandler == null)
            return;
        eventHandler((object)this, e);
    }
}
公共密封类ProgressEx:IProgress
{
专用只读SynchronizationContext\u SynchronizationContext;
私有只读操作处理程序;
私有只读SendOrPostCallback _invokeHandler;
公共事件处理程序已更改;
public ProgressEx(同步上下文同步上下文)
{
//来自Progress.cs
//_synchronizationContext=synchronizationContext.CurrentNoFlow??ProgressStatics.DefaultContext;
_synchronizationContext=syncContext;
_invokeHandlers=新的SendOrPostCallback(invokeHandlers);
}
public ProgressEx(SynchronizationContext SynchContext,操作处理程序)
:此(同步上下文)
{
if(handler==null)
抛出新的ArgumentNullException(“处理程序”);
_handler=handler;
}
私有void OnReport(T值)
{
//问题:对编译器生成的字段的引用
if(_handler==null&&ProgressChanged==null)
返回;
_synchronizationContext.Send(_invokeHandler,(对象)值);
}
无效IProgress.报告(T值)
{
报告(价值);
}
私有void调用句柄(对象状态)
{
te=(T)状态;
Action=\u处理程序;
//问题:对编译器生成的字段的引用
EventHandler EventHandler=ProgressChanged;
如果(操作!=null)
行动(e);
if(eventHandler==null)
返回;
eventHandler((对象)this,e);
}
}
这意味着ProgressEx.Report将在返回之前等待方法完成。也许不是所有情况下的最佳解决方案,但在这种情况下它对我有效


要调用它,只需使用SynchronizationContext.Current创建ProgressEx作为构造函数的参数。但是,它必须在UI线程中创建,以便传入正确的SynchronizationContext。例如,
newprogressex(SynchronizationContext.Current)

无法在此处重现您的问题。在任务完成之前,执行不会传递任何
等待
操作符。我猜你的错误在更高的地方。您的方法是否被多次调用?请编辑问题以显示其调用方式。它一直是异步的,到处都有等待。有可能,我在其他地方有bug,只是现在已经快一个星期找不到了。这应该行得通。发布任务代码。也许lambda主体会返回。进一步挖掘之后,我猜您的问题可能是
progressCallback.Report()
。此方法肯定不会等待事件处理程序完成,因为它看起来像是在线程池上运行的处理程序。这意味着您的进度事件处理程序可能会与循环的下一次迭代同时执行,这听起来像您所描述的。它看起来确实在UI应用程序的主线程上运行,这很有意义。在控制台程序上进行测试。在任何情况下,您的
async
方法都是在线程池线程上运行的。这是同样的想法。调用
Report()
Task
正在等待,但是
Report()
调用正在调用另一个线程上的事件处理程序并返回。事件处理程序仍将与您的下一个循环迭代一起运行。实际上,这破坏了IProgress,IProgress应该以线程安全的方式向需要通知的人报告进度,即不强制线程和侦听器之间进行任何同步。另一方面,这个类将阻塞甚至可能死锁等待订阅者。为什么不直接调用'progressCallback.Report',而不尝试将其包装到任何任务中?我已经将其包装到一个任务中,等待它完成。但是现在我发现我做得不对,所以我将尝试在没有Task.Run的情况下调用它。
public sealed class ProgressEx<T> : IProgress<T>
{
    private readonly SynchronizationContext _synchronizationContext;
    private readonly Action<T> _handler;
    private readonly SendOrPostCallback _invokeHandlers;

    public event EventHandler<T> ProgressChanged;

    public ProgressEx(SynchronizationContext syncContext)
    {
        // From Progress.cs
        //_synchronizationContext = SynchronizationContext.CurrentNoFlow ?? ProgressStatics.DefaultContext;
        _synchronizationContext = syncContext;
        _invokeHandlers = new SendOrPostCallback(InvokeHandlers);
    }

    public ProgressEx(SynchronizationContext syncContext, Action<T> handler)
        : this(syncContext)
    {
        if (handler == null)
            throw new ArgumentNullException("handler");
        _handler = handler;
    }

    private void OnReport(T value)
    {
        // ISSUE: reference to a compiler-generated field
        if (_handler == null && ProgressChanged == null)
            return;
        _synchronizationContext.Send(_invokeHandlers, (object)value);
    }

    void IProgress<T>.Report(T value)
    {
        OnReport(value);
    }

    private void InvokeHandlers(object state)
    {
        T e = (T)state;
        Action<T> action = _handler;
        // ISSUE: reference to a compiler-generated field
        EventHandler<T> eventHandler = ProgressChanged;
        if (action != null)
            action(e);
        if (eventHandler == null)
            return;
        eventHandler((object)this, e);
    }
}