在過去的3-4個月裏,我發現,在默認情況下或者只是巧合,我所有的RxUI observables(.Subscribe)都是在各種對象的構造函數(代碼)中創建的。然而,該應用程序還大量使用後臺任務來監視各種流並採取行動(更新UI,創建事務等),並且有時這些任務需要中止某些事務。所以,我只是想知道哪裏是實例化中止指令(標誌)的「偵聽器」的最佳「地點」?在事務對象創建時,還是在監視流的「監督」對象內?如果在交易中,對績效和處置有什麼影響?我知道這是一個相當寬泛的問題,但我希望有人能夠推薦適當的模式。任何指針,評論贊賞。RxUI - 爲每個事務或流處理對象創建一個偵聽器會更好嗎?
請參閱下面的實體模型代碼:
using System;
using System.Threading.Tasks;
using System.Threading;
using ReactiveUI;
using UserSettingsClassLibrary;
namespace fxR.UTILITIES.MockCode
{
public class MockRxUI_AbortTransaction : ReactiveObject { } // ignore this class
public class ManageTransactions : ReactiveObject
{
// properties
CancellationTokenSource ctTransactionPosition;
// constructor
public ManageTransactions()
{
// initialise
ctTransactionPosition = new CancellationTokenSource();
}
// methods
public async Task OpenTransaction(MyStreamProcessingObject sPO, string user, string openTransactionAction)
{
// ... create transaction object, db log, etc
// open a 'listener' in case this Transaction is aborted
if (user.Contains("/"))
{
sPO.WhenAnyValue(x => x.ActiveObject.AbortTrade)
.Log(this, "TransactionOpen -> Abort trigger ")
.Subscribe(abort =>
{
if (sPO.ActiveObject.TradeOpen && abort)
{
// abort
}
});
}
}
}
// the OpenTransaction method above would be called from elsewhere in the app, eg
public class SomeOtherObject : ReactiveObject
{
ManageTransactions _manageTransactions;
MyStreamProcessingObject _sPO;
public SomeOtherObject(MyStreamProcessingObject sPO)
{
_sPO = sPO;
_manageTransactions = new ManageTransactions();
}
public async Task DoSomethingAsync()
{
await _manageTransactions.OpenTransaction(_sPO, Environment.UserName + "/" + GetType().Name, "TransactionAction").ConfigureAwait(false);
}
}
// ================================================================================================
// OR, open a 'listener' on the Stream Processing Object when it is constructed (first initialised)
// ================================================================================================
public class MyStreamProcessingObject : ReactiveObject
{
// object properties
private ActiveObject _activeObject;
public ActiveObject ActiveObject
{
get { return _activeObject; }
set { this.RaiseAndSetIfChanged(ref _activeObject, value); }
}
// constructor
public MyStreamProcessingObject()
{
// listen for Transaction abort status
this.WhenAnyValue(x => x.ActiveObject.AbortTrade)
.Log(this, "Log -> ActiveObject.AbortTransaction")
.Subscribe(async abort =>
{
if (abort)
{
await Task.Run(async() => await AbortOpenAutoTransaction().ConfigureAwait(false));
}
});
}
// methods
private async Task AbortOpenAutoTransaction()
{
var ok = false;
// await some abort code, if all ok, set ok = true;
if (ok) ActiveObject.AbortTrade = false;
}
}
}
您的代碼沒有按更好沒有任何意義。你已經聲明'OpenTransaction'是異步的並返回類型'Task',但你沒有'await'調用或返回語句。訂閱電話顯然泄露了IDisposables。糟糕的代碼從一開始。 – bradgonesurfing