好吧,我有一个 Windows 窗体应用程序,其中包含一个与我的应用程序并行运行的任务 ( System.Thread.Tasks )。在某些时候,此任务必须等待按钮单击(位于主线程中)并从此按钮捕获数据。我有一个代码,令人惊讶的是它工作得很好。但我相信这不是最好的方法,我认为我应该使用事件来实现这一点,但说实话,我刚刚开始学习事件,所以我仍然有点困惑。如果我是对的,请告诉我我能做些什么来让它变得更好。
这是我的代码的示例:
bool BooleanHelper = false;
int ButtonData;
private void MyButton_Click(object sender, EventArgs e) {
BooleanHelper = true;
ButtonData = 5; //example
}
private void MyForm_Shown(object sender, EventArgs e) {
Task t = Task.Run(()=>{
while(!BooleanHelper){} //this can't be a good pratice .__.
// now if the program reaches this line, it means that we can use the ButtonData.
});
}
Run Code Online (Sandbox Code Playgroud)
使用 TaskCompletionSource 创建一个任务,您可以控制它何时完成:
\n\nTaskCompletionSource<int> buttonTcs = new TaskCompletionSource<int>();\n\nprivate void MyButton_Click(object sender, EventArgs e)\n{\n buttonTcs.SetResult(5);\n}\n\nprivate async void MyForm_Shown(object sender, EventArgs e)\n{\n var buttonData = await buttonTcs.Task;\n\n // now if the program reaches this line, it means that we can use the ButtonData.\n}\nRun Code Online (Sandbox Code Playgroud)\n\n我不知道\xe2\x80\x99t你的MyForm_Shown中的任务是否只是因为你使用了忙碌的等待。如果它确实需要长时间运行的东西,则需要将其包装在 Task.Run 中,而不仅仅是将等待移动到任务中。
\n| 归档时间: |
|
| 查看次数: |
1584 次 |
| 最近记录: |