对具有编辑UI

时间:2018-11-09 07:52:28

标签: c# winforms asynchronous task

我试图在这里找到解决我问题的方法,但是没有结果(或者我只是没有正确地解决问题),所以如果有人可以帮助/解释我将非常感激。

我正在为使用Win Form的系统管理员开发工具,现在我需要在后台运行的所选计算机上创建一个连续的ping。 UI上有一个在线状态指示器,我需要使用背景ping进行编辑。所以现在我处于这种状态:

A级(获胜表格):

ClassB activeRelation = new ClassB();

public void UpdateOnline(Relation pingedRelation)
{
    //There is many Relations at one time, but form shows Info only for one...
    if (activeRelation == pingedRelation)
    {
        if (p_Online.InvokeRequired)
        {
            p_Online.Invoke(new Action(() =>
                p_Online.BackgroundImage = (pingedRelation.Online) ? Properties.Resources.Success : Properties.Resources.Failure
            ));
        }
        else
        {
            p_Online.BackgroundImage = (pingedRelation.Online) ? Properties.Resources.Success : Properties.Resources.Failure;
        }
    }
}

//Button for tunring On/Off the background ping for current machine
private void Btn_PingOnOff_Click(object sender, EventArgs e)
{
    Button btn = (sender is Button) ? sender as Button : null;

    if (btn != null)
    {
        if (activeRelation.PingRunning)
        {
            activeRelation.StopPing();
            btn.Image = Properties.Resources.Switch_Off;
        }
        else
        {
            activeRelation.StartPing(UpdateOnline);
            btn.Image = Properties.Resources.Switch_On;
        }
    }
}

B类(代表与某台计算机的关系的类)

private ClassC pinger;    

public void StartPing(Action<Relation> action)
{
    pinger = new ClassC(this);
    pinger.PingStatusUpdate += action;
    pinger.Start();
}

public void StopPing()
{
    if (pinger != null)
    {
        pinger.Stop();
        pinger = null;
    }
}

C类(后台Ping类)

private bool running = false;
private ClassB classb;
private Task ping;
private CancellationTokenSource tokenSource;
public event Action<ClassB> PingStatusUpdate;

public ClassC(ClassB classB)
{
    this.classB = classB;
}

public void Start()
{
    tokenSource = new CancellationTokenSource();
    CancellationToken token = tokenSource.Token;

    ping = PingAction(token);
    running = true;
}

public void Stop()
{
    if (running)
    {
        tokenSource.Cancel();
        ping.Wait(); //And there is a problem -> DeadLock
        ping.Dispose();
        tokenSource.Dispose();
    }

    running = false;
}

private async Task PingAction(CancellationToken ct)
{
    bool previousResult = RemoteTasks.Ping(classB.Name);
    PingStatusUpdate?.Invoke(classB);

    while (!ct.IsCancellationRequested)
    {
        await Task.Delay(pingInterval);

        bool newResult = RemoteTasks.Ping(classB.Name);

        if (newResult != previousResult)
        {
            previousResult = newResult;
            PingStatusUpdate?.Invoke(classB);
        }
    }
}

所以当我取消令牌并等待Wait()完成任务时,问题就陷入了僵局->它仍在运行,但是Task中的While(...)正确完成了。

1 个答案:

答案 0 :(得分:4)

您有一个死锁,因为ping.Wait();阻止了UI线程。

您应该使用await异步等待任务。

因此,如果Stop()是事件处理程序,则将其更改为:

public async void Stop() // async added here
{
    if (running)
    {
        tokenSource.Cancel();
        await ping; // await here
        ping.Dispose();
        tokenSource.Dispose();
    }

    running = false;
}

如果不是:

public async Task Stop() // async added here, void changed to Task
{
    if (running)
    {
        tokenSource.Cancel();
        await ping; // await here
        ping.Dispose();
        tokenSource.Dispose();
    }

    running = false;
}

@JohnB 所述,异步方法的后缀应为Async,因此该方法应命名为StopAsync()

类似的问题和解决方案在这里说明-Do Not Block On Async Code

您应避免同步等待任务,因此应始终将await与任务一起使用,而不是Wait()Result。另外,如 @Fildor 所指出的那样,您应始终使用async-await来避免这种情况。