2010-03-22 47 views
0

我有異步操作此示例代碼(從interwebs複製)將取消能力和異常處理異步代碼

public class LongRunningTask 
{ 
    public LongRunningTask() 
    { 
    //do nowt 
    } 
    public int FetchInt() 
    { 
     Thread.Sleep(2000);   
     return 5; 
    } 
} 

public delegate TOutput SomeMethod<TOutput>(); 
public class GoodPerformance 
{ 
    public void BeginFetchInt() 
    { 
     LongRunningTask lr = new LongRunningTask(); 
     SomeMethod<int> method = new SomeMethod<int>(lr.FetchInt); 

     // method is state object used to transfer result 
     //of long running operation 
     method.BeginInvoke(EndFetchInt, method); 

    } 

    public void EndFetchInt(IAsyncResult result) 
    {   
     SomeMethod<int> method = result.AsyncState as SomeMethod<int>;   
     Value = method.EndInvoke(result); 

    } 
    public int Value { get; set; } 
} 

我試圖所需的aysnc頁面屬性的其他異步方法,他們也似乎取消的話其他頁面元素(點擊按鈕),這種方法似乎工作。

我想爲longRunningTask類添加取消功能和異常處理,但不要呃,真的知道如何。

回答

2

在例如:

public class ValueEventArgs : EventArgs 
{ 
    public int Value { get;set;} 
} 
public class ExceptionEventArgs : EventArgs 
{ 
    public Exception Exception { get;set;} 
} 
public class LongRunningTask 
{ 
    private bool canceled = false; 

    public event EventHandler<ValueEventArgs> Completed = delegate {} 
    public event EventHandler<ExceptionEventArgs> GotError = delegate {} 

    public void Cancel() 
    { 
     canceled = true; 
    } 

    public void FetchInt() 
    { 
     try 
     { 
      int result = 0; 
      for (int i = 0; i < 1000; i++) 
      { 
       if (canceled) 
        return; 
       result++; 
      } 
      Completed(this, new ValueEventArgs {Value = result}); 
     } 
     catch(Exception exc) 
     { 
      GotError(this, new ExceptionEventArgs { Exception = exc }); 
     } 
    } 

    public void BeginFetchInt() 
    { 
     ThreadPool.QueueUserWorkItem(i => FetchInt()); 
    } 
} 

而且地方:

LongRunningTask task = new LongRunningTask(); 
    task.Completed +=new EventHandler<ValueEventArgs>(task_Completed); 
    task.GotError +=new EventHandler<ExceptionEventArgs>(task_GorError); 
    task.BeginFetchInt(); 
    //in any moment until it calculates you may call: 
    task.Cancel(); 
+0

最優秀的,和簡潔! – Rob 2010-03-23 15:53:10