Skip to content

Instantly share code, notes, and snippets.

Created June 19, 2012 03:30
Show Gist options
  • Save anonymous/2952140 to your computer and use it in GitHub Desktop.
Save anonymous/2952140 to your computer and use it in GitHub Desktop.
TaskFactoryWithUIUpdates
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TestTaskFactory
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
// New up the ProcessingForm so that it can be shown/hidden
// when reports are generated
ProcessingNotificationForm = new ProcessingForm();
// Just for testing, let's set a random sleep timer to delay 5 seconds
SleepTimer = 5000;
// Also, let's load the OrdersDataGridView with bogus data
var orders = new Orders
{
new Order { OrderNumber = 1, Price = 9.99, Product = "Apples" },
new Order { OrderNumber = 2, Price = 3.99, Product = "Bananas" },
new Order {OrderNumber = 3, Price = 4.50, Product = "Ice"}
};
// Bind
OrdersDataGridView.DataSource = orders;
}
// Add variables
public int SleepTimer { get; set; }
private ProcessingForm ProcessingNotificationForm { get; set; }
private void HideProcessingNotificationForm(bool results)
{
// If the task successfully completed, do something
if (results)
{
MessageBox.Show(@"What a success!", @"Testing Things Out");
// Probably should replace this message box with something meaningful
}
// ***** Don't forget to hide the form regardless of the exception.
// ***** This is so that the user can now interact with the app again.
ProcessingNotificationForm.Hide();
}
// Generates the invoice for the order
private void GenerateReportButtonClick(object sender, EventArgs e)
{
// If no row was selected in the order, let's bonk out of this method.
if (OrdersDataGridView.SelectedRows.Count < 1)
{
MessageBox.Show(@"You must choose an order before generating an invoice.", @"Testing Things Out");
return;
}
// Get the selected row and it's values so we can update the
// ProcessingNotificationForm values
var selectedRow = OrdersDataGridView.SelectedRows[0];
var orderNumber = selectedRow.Cells[0].Value;
var productName = selectedRow.Cells[1].Value;
ProcessingNotificationForm.TaskName = " order " + orderNumber + " for " + productName;
// Show the ProcessingNotificationForm
ProcessingNotificationForm.Show();
// Set our Task to run concurrently with the main thread (UI)
// and allow our task to callback to HideProcessingNotificationForm
var uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
Task.Factory.StartNew<bool>(ExecuteBackgroundWork).ContinueWith(ca => HideProcessingNotificationForm(ca.Result), uiScheduler);
}
// Special method to execute background work
private bool ExecuteBackgroundWork()
{
// Establish our return value
var rtn = false;
try
{
// Let's simulate processing a report
Thread.Sleep(SleepTimer);
// Just to throw a wrench into things, let's assume something
// happens while generating the report
throw new Exception(@"Something really bad happened.");
rtn = true;
}
catch (Exception ex)
{
// For an exception, we need to log something. In our case,
// we'll show a message box. However, the message box will
// appear below the ProcessingForm as this thread doesn't
// have direct UI access and cannot bubble this to the front
// unless we pass back the message to the main (UI) thread
// and show the message box there (which is a possibility).
MessageBox.Show(ex.Message, @"Testing Things Out");
}
// Return our return value
return rtn;
}
}
}
namespace TestTaskFactory
{
partial class MainForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.GenerateReportButton = new System.Windows.Forms.Button();
this.OrdersDataGridView = new System.Windows.Forms.DataGridView();
((System.ComponentModel.ISupportInitialize)(this.OrdersDataGridView)).BeginInit();
this.SuspendLayout();
//
// GenerateReportButton
//
this.GenerateReportButton.Location = new System.Drawing.Point(253, 206);
this.GenerateReportButton.Name = "GenerateReportButton";
this.GenerateReportButton.Size = new System.Drawing.Size(116, 23);
this.GenerateReportButton.TabIndex = 0;
this.GenerateReportButton.Text = "Generate Report";
this.GenerateReportButton.UseVisualStyleBackColor = true;
this.GenerateReportButton.Click += new System.EventHandler(this.GenerateReportButtonClick);
//
// OrdersDataGridView
//
this.OrdersDataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.OrdersDataGridView.Location = new System.Drawing.Point(12, 12);
this.OrdersDataGridView.Name = "OrdersDataGridView";
this.OrdersDataGridView.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
this.OrdersDataGridView.Size = new System.Drawing.Size(357, 177);
this.OrdersDataGridView.TabIndex = 3;
//
// MainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(381, 240);
this.Controls.Add(this.OrdersDataGridView);
this.Controls.Add(this.GenerateReportButton);
this.Name = "MainForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Form1";
((System.ComponentModel.ISupportInitialize)(this.OrdersDataGridView)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button GenerateReportButton;
private System.Windows.Forms.DataGridView OrdersDataGridView;
}
}
using System.Collections.Generic;
namespace TestTaskFactory
{
public class Orders : List<Order> { }
public class Order
{
public int OrderNumber { get; set; }
public string Product { get; set; }
public double Price { get; set; }
}
}
using System;
using System.Windows.Forms;
namespace TestTaskFactory
{
public partial class ProcessingForm : Form
{
public string TaskName { get; set; }
public ProcessingForm()
{
InitializeComponent();
//http://uorcdn.com/general/images/processingbar.gif
}
protected override void OnEnter(EventArgs e)
{
webBrowser1.Url = new Uri(Environment.CurrentDirectory + "\\test.htm?taskName=" + TaskName);
base.OnEnter(e);
}
protected override void OnActivated(EventArgs e)
{
webBrowser1.Url = new Uri(Environment.CurrentDirectory + "\\test.htm?taskName=" + TaskName);
base.OnActivated(e);
}
protected override void OnLostFocus(EventArgs e)
{
base.OnLostFocus(e);
this.Focus();
}
protected override void OnDeactivate(EventArgs e)
{
base.OnDeactivate(e);
this.Focus();
}
}
}
using System;
using System.Windows.Forms;
namespace TestTaskFactory
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title></title>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
// Simple function borrowed from a StackOverflow post at
// http://stackoverflow.com/questions/901115/get-query-string-values-in-javascript
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if (results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
</script>
</head>
<body style="padding: 0px; margin: 0px; border: 1px solid black;">
<div style="padding: 3px; font-family: Tahoma; text-align: center; color: Blue;">
Processing <span id="taskName"></span>
</div>
<script type="text/javascript">
$(document).ready(function () {
// After the document is loaded, let's get the querystring parameter
// and update the span called taskName.
$("#taskName").html(getParameterByName("taskName"));
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment