Skip to main content
 首页 » 编程设计

c#之实现具有中止能力的方法

2024年02月13日12dudu

如何实现具有中止能力的方法?

假设我有一个网格,当数据加载时,网格开始计算总计并将它们显示在其下方的另一个网格上。我想在加载数据后立即开始计算总数。

我尝试使用线程,但出现了一个问题:
当我快速点击加载按钮两次时,第一次线程开始工作,第二次我收到一条错误消息,提示线程正忙。

我需要实现一些可以中止并重新开始的方法。

请您参考如下方法:

为此我确实会使用线程。根据您的 .NET 框架,您可以首先设置一个 IProgress 对象,该对象可用于从后台线程池线程提供 UI 更新。所以首先你可以创建

IProgress<object> progressIndicator = 
    new Progress<object>(ReportProgress); 

ReportProgress 是一些方法

public void ReportProgress(object o) { /* Update UI components here on the Main UI thread */ } 

现在,要开始工作并提供取消支持,您可以做一些类似的事情

CancellationTokenSource source = new CancellationTokenSource(); 
CancellationToken token = source.Token; 
Task task = Task.Factory.StartNew(() =>  
    { 
        // Do your work here and provide cancellation support. 
        for (int i = 0; i < someMaxValue; ++i) 
        { 
            // Update the UI if required. 
            progressIndicator.ReportProgress(someObject); 
 
            // No check for you cancellation condition... 
            if (source != null && someCancelCondition) 
                source.Cancel(); // This will throw a CancellationException(). 
        } 
    }, token,  
       TaskCreationOptions.None,  
       TaskScheduler.Default) 
           .ContinueWith(ant =>  
           { 
                // Here you must handle you exceptions and trap your cancellation.  
           }); 

有关详细信息,请参阅 J. Albahari's Threading tutorial .

希望对您有所帮助。