Ragazzi vorrei porvi una domanda...come faccio a sospendere un evento mentre è in esecuzione?Mi spiego:
Ho provato a creare un'applicativo per la lettura dei file XML e ho trovato un file che contiene molte "stringhe" e il programma ci metteva qlk minuto per stamparle tutte...allora mi è sorta la domanda:E' possibile fermare questo evento di lettura del file mentre è in esecuzione?Non vorrei usare i Thread,ma ho sentito parlare del backgroundworker e del fatto che sia molto più semplice tramite questo metodo.Vi presento il codice ovviamente errato,ma spero che possiate capire ciò che volevo fare :-):
codice:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
namespace ApriFileXML
{
public partial class Form1 : Form
{
XmlTextReader fileX ;
public Form1()
{
InitializeComponent();
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.WorkerSupportsCancellation= true;
}
private void but_sfoglia_Click(object sender, EventArgs e)
{
ApriFileDialog.Filter = "File xml|*.xml";
if (ApriFileDialog.ShowDialog() == DialogResult.OK)
{
TxTpercorsoFile.Text = ApriFileDialog.FileName;
}
}
private void but_visualizza_Click(object sender, EventArgs e)
{
TxTletturaFile.Clear();
try
{
fileX = new XmlTextReader(TxTpercorsoFile.Text);
backgroundWorker1.RunWorkerAsync();
backgroundWorker1.DoWork+=new DoWorkEventHandler(backgroundWorker1_DoWork);
}
catch (ArgumentException)
{
MessageBox.Show("Non hai selezionato nessun file XML", "Errore!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (FileNotFoundException)
{
MessageBox.Show("File non trovato", "Errore!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void but_stop_Click(object sender, EventArgs e)
{
if (backgroundWorker1.WorkerSupportsCancellation == true)
{
backgroundWorker1.CancelAsync();
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
while (fileX.Read())
{
if (worker.CancellationPending == true)
{
e.Cancel=true;
break;
}
TxTletturaFile.AppendText("Nome:" + fileX.Name);
TxTletturaFile.AppendText("BaseURI:" + fileX.BaseURI);
TxTletturaFile.AppendText("LocalName:" + fileX.LocalName);
TxTletturaFile.AppendText("AttributeCount:" + fileX.AttributeCount);
TxTletturaFile.AppendText("LineNumber:" + fileX.LineNumber);
TxTletturaFile.AppendText("NodeType:" + fileX.NodeType);
TxTletturaFile.AppendText("\n--\n");
}
}
}
}