0
類
我有這個Singleton
持有我ObservableCollection<MyData>
作爲memeber:填充我的項目源的ListView從
public sealed class Singleton
{
private static volatile Singleton instance;
private static object syncRoot = new Object();
public ObservableCollection<MyData> Files { get; private set; }
private Singleton()
{
Files = new ObservableCollection<MyData>();
}
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}
}
從主窗體類聲明:
ObservableCollection<MyData> Files;
而且這裏的構造函數之後:
Files= Singleton.Instance.Files;
XAML:
<ListView ItemsSource="{Binding Files}" />
現在,當用戶選擇文件,我要檢查每個文件:
private static void Check(IEnumerable<string> files)
{
CancellationTokenSource tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.Token;
Task task = Task.Factory.StartNew(() =>
{
try
{
Parallel.ForEach(files,
new ParallelOptions
{
MaxDegreeOfParallelism = 1
},
file =>
{
ProcessFile(file);
});
}
catch (Exception)
{ }
}, tokenSource.Token,
TaskCreationOptions.None,
TaskScheduler.Default).ContinueWith
(t =>
{
}
, TaskScheduler.FromCurrentSynchronizationContext()
);
}
和:
private static void ProcessFile(string file)
{
// Lets assume that i want to add this file into my `ListView`
MyData data = new .....
Singleton.Instance.Files.Add(data);
}
當我添加文件到我的列表沒有happenning這一點後,所以。
您是否設置了主窗體類的'DataContext'?例如。 'Files = Singleton.Instance.Files; this.DataContext = this;' –
是的,Files = Singleton.Instance.Files; –
檢查'ProcessFile'中是否有TargetInvokationException。將項目添加到ObservableCollection <>'必須在創建集合的同一個線程中發生。所以在你的情況下,UI線程...你可以使用Application.Current.Dispatcher.Invoke(()=> Singleton.Instance.Files.Add(data))'來確保。 –