I am Making C# WPF Application That contains CSV Writing.
But, I wanna give some delays. But When i use
Thread.Sleep(ms),
UI freezes and Windows says that This Program has been Stopped.
So, I found some Alternatives like
private static DateTime Delay(int MS)
{
DateTime ThisMoment = DateTime.Now;
TimeSpan duration = new TimeSpan(0, 0, 0, 0, MS);
DateTime AfterWards = ThisMoment.Add(duration);
while (AfterWards >= ThisMoment)
{
if (System.Windows.Application.Current != null)
{
System.Windows.Application.Current.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Background, new Action(delegate { }));
}
ThisMoment = DateTime.Now;
}
return DateTime.Now;
}
But,when I use this method, The Program just Stops.
This is Button Code that makes, writes CSV File.
private void button_Click(object sender, RoutedEventArgs e)
{
try
{
System.IO.StreamWriter file = new System.IO.StreamWriter(#"New.csv");
int a = 1;
file.WriteLine("Delta, Theta");
while (a < 20)
{
file.WriteLine("{0}, {1}", TGLatestData.EegPowerDelta, TGLatestData.EegPowerTheta);
a++;
file.Close();
Thread.Sleep(3000); //Delay(3000); When I use Alternative way.
}
}
catch (Exception ex)
{
throw new ApplicationException("Broken", ex);
}
}
The Main Question that I want to know is how to delay some seconds without Freezing UI. Sorry for Bad Grammar.
Make your click handler async. Then you can use Task.Delay, which will not block the thread.
private async void button_Click(object sender, RoutedEventArgs e)
{
try
{
System.IO.StreamWriter file = new System.IO.StreamWriter(#"New.csv");
int a = 1;
file.WriteLine("Delta, Theta");
while (a < 20)
{
file.WriteLine("{0}, {1}", TGLatestData.EegPowerDelta, TGLatestData.EegPowerTheta);
a++;
file.Close();
await Task.Delay(3000);
}
}
catch (Exception ex)
{
throw new ApplicationException("Broken", ex);
}
}
By the way, here's one way to fix your exception:
private async void button_Click(object sender, RoutedEventArgs e)
{
const string fileName = #"New.csv";
try
{
File.AppendAllText(fileName, "Delta, Theta");
for (var a=1; a<20; a++)
{
var text = string.Format("{0}, {1}", TGLatestData.EegPowerDelta, TGLatestData.EegPowerTheta);
File.AppendAllText(fileName, text);
await Task.Delay(3000);
}
}
catch (Exception ex)
{
throw new ApplicationException("Broken", ex);
}
}
private async void CSVexport_Click(object sender, RoutedEventArgs e) //to use Await Task.Delay(ms) Option
{
try
{
SaveFileDialog saveAsfile = new SaveFileDialog(); //Save As File
saveAsfile.InitialDirectory = #"C:\";
saveAsfile.Title = "Save As File";
saveAsfile.Filter = "CSV Document(*.csv)|*.csv|All Files(*.*)|*.*";
saveAsfile.DefaultExt = "csv";
saveAsfile.AddExtension = true;
if (saveAsfile.ShowDialog() == System.Windows.Forms.DialogResult.OK) //Save As File Function
{
GaugeSignal.Value = 1;
if (TGLatestData.PoorSignal != -1)
{
var SignalQuality = Math.Round((200D - TGLatestData.PoorSignal) / 2D, 1);
if (SignalQuality < 0) SignalQuality = 0;
GaugeSignal.Value = SignalQuality;
TGLatestData.PoorSignal = TGLatestData.PoorSignal;
}
SQZero.Visibility = 0;
CSVexport.Visibility = Visibility.Hidden;
FileStream filestream = new FileStream(saveAsfile.FileName, FileMode.Create, FileAccess.Write);
System.Windows.MessageBox.Show("CSV Writing...\nIf you want to stop Writing CSV, Click SQ to 0 Button,", "CSV Writing...", MessageBoxButton.OK, MessageBoxImage.Warning);
System.IO.StreamWriter file = new System.IO.StreamWriter(filestream);
int time = 1000;
file.WriteLine("Signal Quality, Delta, Theta, Alpha1, Alpha2, Beta1, Beta2, Gamma1, Gamma2, Attention, Meditation, Mental Effort, Task Familiarity, Task Difficulty, Blink Strength");
while (true) //infinite loop
{
double Check_Signal_Zero_To_Stop = GaugeSignal.Value;
file.WriteLine("{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {11}, {12}, {13}, {14}", GaugeSignal.Value, TGLatestData.EegPowerDelta, TGLatestData.EegPowerTheta, TGLatestData.EegPowerAlpha1, TGLatestData.EegPowerAlpha2, TGLatestData.EegPowerBeta1, TGLatestData.EegPowerBeta2, TGLatestData.EegPowerGamma1, TGLatestData.EegPowerGamma2, TGLatestData.Attention, TGLatestData.Meditation, TGLatestData.MentalEffort, TGLatestData.TaskFamiliarity, TGLatestData.TaskDifficulty, TGLatestData.BlinkStrength);
await Task.Delay(time); //Delay Without FreezingUI (need async)
if (Check_Signal_Zero_To_Stop == 0)
{
file.Close(); //if you click SQ to 0, Do file.Close
while (true) await Task.Delay(1000000000);
}
}
}
}
catch (ApplicationException ex)
{
throw new ApplicationException("This Program is Get Broken", ex);
}
}
I changed private void to 'private async void' to use Await Task.Delay(ms) instead of Thread.Sleep(ms) and I also Made Stop Button to get out of infinite loop.
Here is SQ to 0 Button Source. If you Click this button, One variable(GaugeSignal.Value) will be 0 and it will stop Writing CSV and Saving modified file.
private async void SQzero_Click(object sender, RoutedEventArgs e)
{
int EndTime = 4000;
SQZero.Visibility = Visibility.Hidden;
System.Windows.MessageBox.Show("Stop Writing CSV... \nWait a Seconds..", "CSV Saving..", MessageBoxButton.OK, MessageBoxImage.Warning);
GaugeSignal.Value = 0;
await Task.Delay(EndTime); //Wait for Delay of CSVexport_btn
System.Windows.MessageBox.Show("CSV Saved!", "CSV Saved", MessageBoxButton.OK, MessageBoxImage.Warning);
CSVexport.Visibility = Visibility.Visible; //to Save another one Again
}
I was Foolish. I used file.Close(); in loop. So, It says IOException. I found other method to avoid them and Finally got it. Thanks to John Wu, Çöđěxěŕ to help me.
I start the parallel for loop process from button click(Start Button). The parallel process going well but at the time I moved another page then I return to current parallel process page,process going well.
I try to stop the Parallel process from another button click(button stop). Is it possible?
protected void btnstart_Click(object sender, EventArgs e)
{
try
{
Parallel.For(0, dtrecord.Rows.Count, pOptions1, (j, pls) =>
{
if (Session["Stop"] != null)
{
pls.Stop();
Session.Remove("Stop2");
Session["ParallelStopped"] = 1;
}
else
{
Checkrecords(dtrecord, ImportFileID, j);
}
});
}
catch (Exception ex)
{
Log.Trace("Error occured in btnstop_Click");
Log.Error(ex.Message);
}
}
protected void btnstop_Click(object sender, EventArgs e)
{
try
{
Session["Stop"] = 1;
Session.Remove("start");
Session["start"] = null;
BindImportfileDetails();
BindImportrecordsdetails(hidimid.Value);
bindimportrecords();
Getrecordstatuscount();
Log.Trace("User has been stopping the import process");
}
catch (Exception ex)
{
Log.Trace("Error occured in btnstop_Click");
Log.Error(ex.Message);
}
}
I'm using C# and Windows Phone 8.1 as Universal.
I Have an issue with BackgroundDownloader. when I start a downloader, it gave me an exception:
Downloading http://localhost/MySong.mp3 to MySong.mp3 with Default priority, a95c00db-738d-4e22-a456-dc30d49b0a3b
A first chance exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll
Exception: The system cannot find the file specified. (Exception from HRESULT: 0x80070002)
here is my code:
private void downladButton_Tapped(object sender, TappedRoutedEventArgs e)
{
PumpUrl(txtUrl.Text);
}
async void PumpUrl(string url)
{
if (!string.IsNullOrEmpty(url) && CheckUrl(url))
StartDownloadMethod(url);
else
await new MessageDialog("Looks like URL is invalid.\r\nPlease check your URL and try again"").ShowAsync();
}
public bool CheckUrl(string URL)
{
Uri source;
if (Uri.TryCreate(URL, UriKind.RelativeOrAbsolute, out source))
return true;
else
return false;
}
public void StartDownloadMethod(string url, string fileName = null)
{
StartDownload(url, BackgroundTransferPriority.Default, false, fileName);
}
private async void StartDownload(string url, BackgroundTransferPriority priority, bool requestUnconstrainedDownload, string fileName = null)
{
Uri source;
if (!Uri.TryCreate(url.Trim(), UriKind.RelativeOrAbsolute, out source))
{
Debug.WriteLine("Invalid URI.");
return;
}
string destination = null;
if (string.IsNullOrEmpty(fileName))
try
{
destination = System.IO.Path.GetFileName(Uri.UnescapeDataString(url)).Trim();
}
catch { }
else
destination = Uri.UnescapeDataString(fileName).Trim();
if (string.IsNullOrWhiteSpace(destination))
{
Debug.WriteLine("A local file name is required.");
return;
}
StorageFile destinationFile = null;
try
{
if (vars.localType == LocalType.SDCard)
destinationFile = await KnownFolders.RemovableDevices.CreateFileAsync(
"Downloads\\Test App\\" + destination, CreationCollisionOption.GenerateUniqueName);
else
destinationFile = await KnownFolders.MusicLibrary.CreateFileAsync(
"Test App\\" + destination, CreationCollisionOption.GenerateUniqueName);
}
catch (FileNotFoundException ex)
{
Debug.WriteLine("Error while creating file: " + ex.Message);
return;
}
catch (Exception ex) { Debug.WriteLine("Error while creating file: " + ex.Message); }
if (destinationFile == null)
return;
BackgroundDownloader downloader = new BackgroundDownloader();
DownloadOperation download = downloader.CreateDownload(source, destinationFile);
Debug.WriteLine(String.Format(CultureInfo.CurrentCulture, "Downloading {0} to {1} with {2} priority, {3}",
source.AbsoluteUri, destinationFile.Name, priority, download.Guid));
download.Priority = priority;
Add(url, destination, download);
if (!requestUnconstrainedDownload)
{
// Attach progress and completion handlers.
await HandleDownloadAsync(download, true);
return;
}
List<DownloadOperation> requestOperations = new List<DownloadOperation>();
requestOperations.Add(download);
UnconstrainedTransferRequestResult result;
try
{
result = await BackgroundDownloader.RequestUnconstrainedDownloadsAsync(requestOperations);
}
catch (NotImplementedException)
{
Debug.WriteLine(
"BackgroundDownloader.RequestUnconstrainedDownloadsAsync is not supported in Windows Phone.");
return;
}
Debug.WriteLine(String.Format(CultureInfo.CurrentCulture, "Request for unconstrained downloads has been {0}",
(result.IsUnconstrained ? "granted" : "denied")));
await HandleDownloadAsync(download, true);
}
private async Task HandleDownloadAsync(DownloadOperation download, bool start)
{
try
{
Debug.WriteLine("Running: " + download.Guid);
bool bb = false;
foreach (DownloadOperation item in DownloadDB.activeDownloads)
{
if (item != null && item.Guid == download.Guid)
{
bb = true;
break;
}
}
if (!bb)
DownloadDB.activeDownloads.Add(download);
Progress<DownloadOperation> progressCallback = new Progress<DownloadOperation>(DownloadProgress);
CancellationTokenSource cts = new CancellationTokenSource();
AppendCancellationTokenSource(download, cts);
if (start)
await download.StartAsync().AsTask(cts.Token, progressCallback);
else
await download.AttachAsync().AsTask(cts.Token, progressCallback);
ResponseInformation response = download.GetResponseInformation();
DownloadDB.RemoveChildByGuid(download.Guid.ToString());
DownloadDB.SaveDB();
Debug.WriteLine(String.Format(CultureInfo.CurrentCulture, "Completed: {0}, Status Code: {1}",
download.Guid, response.StatusCode));
}
catch (TaskCanceledException taskCanceled)
{
Debug.WriteLine("TaskCanceledException: " + download.Guid + "\t" + taskCanceled.Message);
DownloadDB.RemoveChildByGuid(download.Guid.ToString());
}
catch (Exception ex)
{
Debug.WriteLine("Exception: " + ex.Message);
}
finally
{
DownloadDB.RemoveChildByGuid(download.Guid.ToString());
DownloadDB.activeDownloads.Remove(download);
}
}
I used my code in other application 3 month ago and it works fine but in this application dosent work. Where I wrong?
Thanks
here are my two functions:
public void SetCompanies()
//set the Companies table from Shret.net DataBase
{
try
{
WebClient webClient = new WebClient();
Uri uri = new Uri("http://api.sherut.net/?method=Company");
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
try
{
webClient.OpenReadAsync(uri);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void webClient_OpenReadCompleted(object sender, OpenWriteCompletedEventArgs e)
{
try
{
DataContractJsonSerializer serializer = null;
var companies = (Companies)serializer.ReadObject(e.Result);
foreach (Company c in companies.data)
{
MessageBox.Show(c.Name + " " + c.CompanyID);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
and this is the error i get:
"No overload for 'webClient_OpenReadCompleted' matches delegate
'System.Net.OpenReadCompletedEventHandler'"
i dont understand why, because i wrote the handler after this function......
Thanks in advance!
OpenReadCompleted doesn't take OpenWriteCompletedEventArgs.
I'm trying to read from a Uri which i created and to display it on windows phone 7 app.
(I'm doing this tutorial:http://msdn.microsoft.com/en-us/windowsmobile/Video/hh237494).
My problem is that the program doesnt get into the OpenReadCompletedEventHandler and i dont know why. (i putted message box in order to debug and i found out that the program doesnt get into the OpenReadCompletedEventHandler). Here is the relevant code:
void myButton_Click(object sender, RoutedEventArgs e)
{
try
{
WebClient webClient = new WebClient();
Uri uri = new Uri("http://localhost:44705/Service1.svc/GetAllBrands");
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
try
{
webClient.OpenWriteAsync(uri);
MessageBox.Show("opening sucsseded");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
MessageBox.Show("OpenRead Handler");
// OpenWriteCompletedEventArgs temp = (OpenWriteCompletedEventArgs)e;
DataContractJsonSerializer serializer = null;
try
{
serializer = new DataContractJsonSerializer(typeof(ObservableCollection<Brand>));
ObservableCollection<Brand> Brands = serializer.ReadObject(e.Result) as ObservableCollection<Brand>;
foreach (Brand b in Brands)
{
int id = b.BrandId;
string name = b.BrandName;
listBrands.Items.Add(id + " " + name);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Thanks in advance!
I have never used this but a quick google takes me to this page on MSDN - http://msdn.microsoft.com/en-us/library/system.net.webclient.openreadcompleted.aspx
This should tell you why it's not working - because you are using a read event for a write operation. You should be using OpenWriteCompletedEventHandler with OpenWriteAsync as per this page on MSDN - http://msdn.microsoft.com/en-us/library/system.net.webclient.openwritecompleted.aspx