简体   繁体   English

net 2 上的 C# 多线程,firebird 数据库取消并重新启动,如何?

[英]C# multithreading on net 2, firebird database cancel and restart, how?

In winform app, I have DataGridView and thread which is loading data from database when user press button.在 winform 应用程序中,我有DataGridView和线程,当用户按下按钮时,它从数据库加载数据。

This loading is done on another thread, I don't know how to make the following scenario:这个加载是在另一个线程上完成的,我不知道如何制作以下场景:

when user press another button, the same procedure starts, with different query, cancelling previous thread and loading data only from second time.当用户按下另一个按钮时,相同的过程开始,不同的查询,取消前一个线程,只从第二次加载数据。

Currently it works in such way, that DataGridView is populated with second query, but after few seconds its repopulated with first query.目前它以这样的方式工作,即DataGridView用第二个查询填充,但几秒钟后它用第一个查询重新填充。 And it shouldn't, first query should be in some way cancelled.它不应该,第一个查询应该以某种方式取消。

How to do that?怎么做?

Below is a basic example how you can achieve the desired behavior.以下是如何实现所需行为的基本示例。 There is no cancelling database query, but there is ignoring results that is not relevant anymore.没有取消数据库查询,但忽略了不再相关的结果。

public static IEnumerable<Row> GetRowsForTheFirstButton()
{
    var token = GridResultsSync.GetCurrentToken();

    // retrieving data
    ...

    if (GridResultsSync.IsTokenRelevant(token))
        return result;
    return null;
}
// exactly the same code for the second method
public static IEnumerable<Row> GetRowsForTheSecondButton()
{
    var token = GridResultsSync.GetCurrentToken();

    // retrieving data
    ...

    if (GridResultsSync.IsTokenRelevant(token))
        return result;

    return null;
}

...
class GridResultsSync
{
    static int _count = 0;
    public static int GetCurrentToken()
    {
        return Interlocked.Increment(ref _count);
    }
    public static bool IsTokenRelevant(int token)
    {
        var currentCount = Interlocked.Increment(ref _count);
        return currentCount - token  <=  2;
    }
}

When you call GetRowsForTheFirstButton() and GetRowsForTheSecondButton() then you check if the result is not null , then you bind the result to grid, if the result is null then do nothing.当您调用GetRowsForTheFirstButton()GetRowsForTheSecondButton() ,检查结果是否为null ,然后将结果绑定到网格,如果结果为 null 则什么都不做。

If you really want to cancel a query to DB then you may consider a little more complex approach.如果您真的想取消对数据库的查询,那么您可以考虑使用更复杂的方法。 It can be done using SqlCommand.Cancel Method or if you are using Entity Framework you can use CancellationToken .可以使用SqlCommand.Cancel 方法完成,或者如果您使用的是Entity Framework ,则可以使用CancellationToken

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM