Skip to content

Instantly share code, notes, and snippets.

@121jigowatts
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 121jigowatts/01018790a337740648db to your computer and use it in GitHub Desktop.
Save 121jigowatts/01018790a337740648db to your computer and use it in GitHub Desktop.
[非同期]Windows Formsで非同期でリストボックスに値を設定する
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
//Pattern.1 Control.BeginInvoke
string[] listCodes1 = { "A", "B", "C", "D", "E", "F", "G", "H" };
foreach (var listCode1 in listCodes1)
{
listBox1.Items.Add(listCode1);
}
if (listBox1.Items.Count > 0)
{
listBox1.SetSelected(0, true);
//非同期実行
var method = new Func<string[]>(() =>
{
string[] result = { "D1", "D2", "D3" };
System.Threading.Thread.Sleep(3000);
return result;
});
method.BeginInvoke(ar =>
{
var result = method.EndInvoke(ar);
//Control.BeginInvoke
listBox2.BeginInvoke((Action)(() =>
{
foreach (var item in result)
{
listBox2.Items.Add(item);
}
}));
}, null);
}
}
}
}
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
//Pattern.2 Task
string[] listCodes1 = { "A", "B", "C", "D", "E", "F", "G", "H" };
foreach (var deptCode in listCodes1)
{
listBox1.Items.Add(deptCode);
}
if (listBox1.Items.Count > 0)
{
listBox1.SetSelected(0, true);
Task<string[]>.Factory.StartNew(() =>
{
string[] result = { "D1", "D2", "D3" };
System.Threading.Thread.Sleep(3000);
return result;
}).ContinueWith(t =>
{
foreach (var item in t.Result)
{
listBox2.Items.Add(item);
}
}, TaskScheduler.FromCurrentSynchronizationContext());
}
}
}
}
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form3 : Form
{
public Form1()
{
InitializeComponent();
//Pattern.3 async/await
SetListBox();
}
public void SetListBox()
{
string[] listCodes1 = { "A", "B", "C", "D", "E", "F", "G", "H" };
foreach (var listCode1 in listCodes1)
{
listBox1.Items.Add(listCode1);
}
if (listBox1.Items.Count > 0)
{
listBox1.SetSelected(0, true);
AsyncMethod();
}
}
public async void AsyncMethod()
{
string[] listCodes2 = await Task<string[]>.Run(() =>
{
string[] result = { "D1", "D2", "D3" };
System.Threading.Thread.Sleep(3000);
return result;
});
foreach (var item in listCodes2)
{
listBox2.Items.Add(item);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment